如何用变量范围解释这个问题?

ser*_*erg 2 javascript scope

为什么第二个函数输出一个空数组?

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)

use*_*716 5

虽然它似乎应该有效,因为赋值从右到左,你需要考虑提升变量声明.

对于解释器,您的代码实际上如下所示:

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)