为什么此代码的输出是242,而不是243

Sus*_*han 1 html javascript

var x = 2;

function fun() {
  x = 3;
  var x = 4;
  document.write(x);
}

document.write(x);

fun()

document.write(x);
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我了解控制流程。为什么输出242在看起来应该是243时会如此。将不胜感激所有帮助。

Mah*_*Ali 6

这是由于吊装。x内部局部变量fun被带到作用域的顶部,然后分配值3 ,然后分配值4。所以line x=3;并没有改变全局变量,而是改变了局部变量。该代码就像

function fun(){
    var x;
    x=3;
    x=4;
    document.write(x);
}
Run Code Online (Sandbox Code Playgroud)


Ful*_*Guy 5

修改时,x=3实际上并不会更改全局变量,x而是会更改功能块中声明的变量(因为var变量具有函数作用域)。由于声明var x是提升到顶部,然后将修改x = 3情况

<script>
      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);
</script>
Run Code Online (Sandbox Code Playgroud)

要在全局范围内真正更改变量,请使用window.x引用它:

<script>
    	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);
</script>
Run Code Online (Sandbox Code Playgroud)

  • 谢啦。您的解释非常清楚! (2认同)