pom*_*421 2 javascript node.js
我对Node(v8.5.0)如何解释这段代码感到非常惊讶:
var a = 5;
var b = 10;
console.log('a = ' + a)
console.log('b = ' + b)
[a, b] = [b, a];
console.log(a);
console.log(b);
Run Code Online (Sandbox Code Playgroud)
回应是
[a, b] = [b, a];
^
TypeError: Cannot set property '10' of undefined
at Object.<anonymous> (/Users/pom/lab/ES6-tests/destructuring.js:25:8)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:201:16)
at bootstrap_node.js:626:3
Run Code Online (Sandbox Code Playgroud)
如果我只在console.log中保留var,则显示正确
console.log(a)
console.log(b)
[a, b] = [b, a];
Run Code Online (Sandbox Code Playgroud)
这是做什么的?
这是左侧参数无效的结果,可能是由于解析问题.
原因是在console.log调用之后你缺少一个分号,这会使解释器混淆并且似乎导致两行代码串联.您可以看到它使用分号可以正常工作,而不是.
console.log("works");
var a = 5;
var b = 10;
console.log('a = ' + a);
console.log('b = ' + b);
[a, b] = [b, a];
console.log(a);
console.log(b);Run Code Online (Sandbox Code Playgroud)
console.log("fails (with no semi-colon)");
var a = 5;
var b = 10;
console.log('a = ' + a)
console.log('b = ' + b)
[a, b] = [b, a];
console.log(a);
console.log(b);Run Code Online (Sandbox Code Playgroud)