【问题标题】:How do I approach variable with string value?如何使用字符串值处理变量?
【发布时间】:2023-01-13 10:51:21
【问题描述】:

我喜欢传递参数并想用它来返回特定的变量

test1 (type) {
    const enable { color: 'blue' }
    const disabled { color: 'red' }
    return type === 'enable' ? enable : disabled
}

例如,我喜欢将 test1 更改为 test2。 我想这样做是因为我有多种类型,这会使代码变得复杂。 有什么办法可以做到这一点?

test2 (type) {
    const enable { color: 'blue' }
    const disabled { color: 'red' }
    return type
}

【问题讨论】:

  • 在变量初始化中需要=const enable = {...}

标签: javascript


【解决方案1】:

使用由 type 值键入的对象。

function test2(type) {
    const vals = {
        enable: { color: 'blue' },
        disable: { color: 'red' }
    };
    return vals[type];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2013-12-14
    • 2018-06-16
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    相关资源
    最近更新 更多