【问题标题】:why can't we add object property names using template strings [duplicate]为什么我们不能使用模板字符串添加对象属性名称[重复]
【发布时间】:2020-04-26 01:09:13
【问题描述】:

我想使用作为变量的属性名称添加或修改对象。

我发现使用动态属性名称的方法是使用方括号,

var x ="hi"

a = {
...a,
[x]:"hello"
}

上述代码有效,对象 a 具有名为“hi”的新属性。

我们可以使用字符串属性名称添加一个新属性,如下所示。

a = {
...a,
"hiwithstring":"hello with string"
}

上面的代码工作正常,因为它是正常的方式。 即使我们不在字符串引号中保留名称,js 引擎也会在内部为我们这样做。

使用字符串插值,我们可以将变量包含到字符串中,如下所示,

var x ="hiWithInterpolation"
 var propName = `${x}`
//now propName is "hiWithInterpolation".

现在我的问题是为什么我们不能使用字符串插值来添加动态属性名称,如下所示?

var x ="hiWithInterpolation"
a = {
...a,
`${x}`:"helloWithINterPolation"
}

上面的代码不起作用并抛出 Uncaught SyntaxError: Unexpected template string。

有人可以解释为什么最后一个例子失败了吗?

【问题讨论】:

  • a = {...a, [${x}]:"foo"} 会工作

标签: javascript object


【解决方案1】:

您需要computed property name

var x = "hiWithInterpolation";
a = {
    ...a,
    [`${x}`]: "helloWithINterPolation"
};

【讨论】:

    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2017-11-08
    • 2010-11-20
    相关资源
    最近更新 更多