如下图,案例1、案例2、案例3access a property包含 computed property name 的对象的.
情况 1 在函数参数中创建这样的对象,而情况 2 在赋值中创建这样的对象。情况 3 在语句中创建这样一个对象。
为什么情况 3 会产生语法错误?
案例1
$ node -e "var other = 'b'; console.log({a: 1, [other]: 2}[other]);"
2
案例2
$ node -e "var other = 'b'; var obj = {a: 1, [other]: 2}[other]; console.log(obj);"
2
案例3
$ node -e "var other = 'b'; {a: 1, [other]: 2}[other];"
[eval]:1
var other = 'b'; {a: 1, [other]: 2}[other];
^
SyntaxError: Unexpected token :
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Object.<anonymous> ([eval]-wrapper:6:22)
at Module._compile (module.js:570:32)
at evalScript (bootstrap_node.js:353:27)
at run (bootstrap_node.js:122:11)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:121:9)
at bootstrap_node.js:504:3
节点版本
$ node --version
v6.11.2
最佳答案
简而言之,您将大括号视为 block statement ,而不是 object .
错误来自 label ,不能是 computed property name ,因为它需要是一个标识符,而不是一个计算属性。
第一个调用被定义为表达式,而在最后一种情况下则不是。
为了防止这种情况,您可以将表达式的大括号括在圆括号中。
eval("var other = 'b'; {a: 1, console.log('block!') };");
console.log(eval("var other = 'b'; ({a: 1, [other]: 2})[other];"));
关于javascript - 计算属性名称上的 JS 属性访问器在表达式与赋值中的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359164/