繁体   English   中英

用于Java范围的Java语言变量提升

[英]Javascript variable hoisting for gobal scope

有人可以解释为什么未定义的打印到控制台而不是4吗?

var a = 4;
function test() {
 if (!a) {
   a = 3;
 }
 console.log(a)
}
undefined

这与variable hoisting无关。

因为你什么也没return 因此,当您在浏览器控制台中执行此代码时,它显示为undefined

要得到4 ,结果是您需要调用test函数并从该函数return a

码:

var a = 4;

function test() {
    if (!a) {
        a = 3;
    }

    console.log(a);

    // Return a from the function, if needed
    return a;
}

// Call function here
test();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM