繁体   English   中英

为什么变量的值在 output 之前没有按预期更新?

[英]Why is a variable's value not updated as expected before being output?

我知道我不应该用这个标题提交问题,但我真的被下面的代码弄糊涂了。 任何人都可以解释为什么最后一行打印 1?

环境:铬 80.0.3987.163

 console.log(foo) // undefined if (true) { foo = 1 console.log(foo) // 1 function foo() { console.log("a") } console.log(foo) // 1, function foo is hoist foo = 2 console.log(foo) // 2 } else { function foo() { console.log("b") } } console.log(foo) // 1, why?

如果删除 function 声明,就可以了。

 console.log(foo) // undefined if (true) { foo = 1 console.log(foo) // 1 foo = 2 console.log(foo) // 2 } else { function foo() { console.log("b") } } console.log(foo) // 2

那么,在 if 块内的 function 声明之后,JS 引擎认为您指的是 function。 如果您更改 function 名称,它应该可以正常工作。

console.log(foo) // undefined
if (true) {
   var foo = 1;
    console.log(foo, 'foo1') // 1
    function foo2() {
        console.log("a")
    }
    console.log(foo, 'still foo1') // 1, function foo is hoist
    foo = 2
    console.log(foo, 'foo2') // 2
} else {
    function foo() {
        console.log("b")
    }
}

console.log(foo) // 1, why?

这个第一个 foo 是全局 scope

after the function with the same name, it was identified as a local scope ie it become a local scope within that function but if you change the function name everything should work normal ie foo will now be of value 2

暂无
暂无

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

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