【问题标题】:Why does object destructuring assignment throw an error when using template strings? [duplicate]为什么使用模板字符串时对象解构赋值会抛出错误? [复制]
【发布时间】:2019-02-25 23:16:05
【问题描述】:

在 JavaScript 中,可以像这样通过对象解构来分配变量:

let a = {b: 2};
let {b} = a;
console.log(b); // 2

有时需要访问的属性不是有效的变量名,在这种情况下可以传递一个替代标识符:

let a = {'words with spaces': 2};
let {'words with spaces': words_without_spaces} = a;
console.log(words_without_spaces); // 2

这适用于单引号字符串和双引号字符串。但是,尝试对模板字符串执行完全相同的操作时会引发错误:

let a = {'words with spaces': 2};
let {`words with spaces`: words_without_spaces} = a;
     ^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected template string

为什么在这里使用模板字符串会导致错误,而其他字符串不会?我知道模板字符串可以预先定义为变量,然后使用计算属性括号传递,但我只是好奇上述代码不起作用的原因是什么。

【问题讨论】:

  • 只是因为属性键必须由 '" 分隔 - 字符串文字而不是模板表达式。
  • 我认为这至少可以部分回答:stackoverflow.com/questions/33194138/…
  • 谢谢,那篇文章回答了我的问题。

标签: javascript syntax template-strings


【解决方案1】:

语言语法允许对象初始化器中的属性名称或赋值的解构左侧是字符串文字,而不是模板。语法就是这样定义的。

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 2010-10-02
    • 2022-07-21
    • 2021-04-13
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多