【问题标题】:Why is the this code's output 242 and not 243 [duplicate]为什么此代码的输出是 242 而不是 243 [重复]
【发布时间】:2019-09-03 05:09:09
【问题描述】:

var x = 2;

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

document.write(x);

fun()

document.write(x);

谁能帮我理解控制流程。为什么输出 242 看起来应该是 243。所有帮助将不胜感激。

【问题讨论】:

  • 函数中的var 声明被解释为好像它出现在函数块的最开始。函数中对x的所有引用都是对局部变量的引用,而不是对全局x的引用。
  • 你确定答案吗?不好意思问了。
  • 很简单,按照变量的作用域打印输出即可。
  • 是的,我确定。您看到它打印 242 对吗?
  • @Lewis 那么你需要了解一下scope

标签: javascript html


【解决方案1】:

当您修改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>

要真正在全局范围内更改变量,请使用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>

【讨论】:

  • 谢谢,伙计。您的解释非常清楚!
【解决方案2】:

这是由于吊装。变量xfun 中是局部变量,它被带到作用域的顶部,然后分配值3,然后分配值4。所以line x=3; 不是在改变全局变量,而是在改变它的局部变量。代码的行为类似于

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

【讨论】:

  • 谢谢你的回答,真的很有帮助。 :)
  • @SushantPradhan 接受您最满意的答案。
猜你喜欢
  • 2016-05-16
  • 2021-03-21
  • 1970-01-01
  • 2019-08-02
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
相关资源
最近更新 更多