[英]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.