为什么第二个函数输出一个空数组?
var global = ["abc"];
function test1() {
var g = global || [];
console.log(g); //outputs: ["abc"]
}
function test2() {
var global = global || [];
console.log(global); //outputs: []
}
最佳答案
虽然它看起来应该有效,因为赋值是从右到左进行的,但您需要考虑变量声明被提升。
对于解释器来说,你的代码实际上是这样的:
function test2() {
var global; // global is undefined
global = global || []; // because undefined is falsey, the [] is assigned
console.log(global); // displays the []
}
关于javascript - 如何用可变范围解释这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7796766/