【发布时间】: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