简体   繁体   English

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

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

I know I should not submit a question with this title, but I am really confused by the following code.我知道我不应该用这个标题提交问题,但我真的被下面的代码弄糊涂了。 anyone can explain why the last line print 1?任何人都可以解释为什么最后一行打印 1?

enviroment: chrome 80.0.3987.163环境:铬 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?

if remove the function declaration, it's OK.如果删除 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

Well, after the function declaration inside the if block, the JS engine thinks that you're referring to the function.那么,在 if 块内的 function 声明之后,JS 引擎认为您指的是 function。 If you change the function name it should work properly.如果您更改 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?

This first foo is the global scope这个第一个 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 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