Why is the this code's output 242 and not 243
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 | var x = 2; function fun() { x = 3; var x = 4; document.write(x); } document.write(x); fun() document.write(x); |
有人能帮我理解控制的流程吗?为什么输出242看起来应该是243。我们将非常感谢您的帮助。
这是因为起重。在
1 2 3 4 5 6 | function fun(){ var x; x=3; x=4; document.write(x); } |
当您修改
1 2 3 4 5 6 7 8 9 10 11 | var x=2; function fun(){ //var x; hoisted to the top; console.log("x is hoisted here and uninitialized value will be", x) x=3; //initialized, actually referring to the variable declared in the function scope var x = 4; //declared but hoisted at the top document.write(x); } document.write(x); fun() document.write(x); |
要在全局范围内真正更改变量,请使用
1 2 3 4 5 6 7 8 9 | var x=2; function fun(){ window.x=3; //modifying the global variable 'x` var x = 4; document.write(x); } document.write(x); fun() document.write(x); |