为什么第二个函数输出一个空数组?
var global = ["abc"];
function test1() {
var g = global || [];
console.log(g); //outputs: ["abc"]
}
function test2() {
var global = global || [];
console.log(global); //outputs: []
}
Run Code Online (Sandbox Code Playgroud)
虽然它似乎应该有效,因为赋值从右到左,你需要考虑提升变量声明.
对于解释器,您的代码实际上如下所示:
function test2() {
var global; // global is undefined
global = global || []; // because undefined is falsey, the [] is assigned
console.log(global); // displays the []
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |