以下HTML / javascript代码中的一些混淆 [英] some confusion in the following HTML/javascript code

查看:79
本文介绍了以下HTML / javascript代码中的一些混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<html>
<body>
<script language="javascript" type="text/javascript">

var x = 1;

function ChangeXto2() {
  x = 2;
}

function ChangeXto3() {
  var x = 3;
}

document.write(x);

ChangeXto2();
document.write(x);

ChangeXto3();
document.write(x);

</script>
</body>
</html>


<!--
the output in the above code is 122. Can you tell why ?? And why the out is not 123 ??

But in the code below the output is 123.
All I did was copy paste the above code and omit the var before x = 3 in function ChangeXto3()
-->


<html>
<body>
<script language="javascript" type="text/javascript">

var x = 1;

function ChangeXto2() {
  x = 2;
}

function ChangeXto3() {
  x = 3;
}

document.write(x);

ChangeXto2();
document.write(x);

ChangeXto3();
document.write(x);

</script>
</body>
</html>


<!--
Why 2 different outputs ?
-->

推荐答案

在第一个示例中,x变量是一个局部变量,以下代码对全局x变量没有影响。这就是输出为122的原因。


In your first example x variable is a local variable and the following code does not effect to your global x variable. That's why the output is 122.

function ChangeXto3() {
  var x = 3;
}





主要的是你申报变量的地方。如果在函数中声明它将是函数的局部变量。如果你在你的函数之外声明它将是全局的。



这是一个解释:

JavaScript函数中的全局和局部变量 [ ^ ]


x是第一个代码块中函数ChangeXto3()中的局部变量..因此在第一个代码块中回答122。
x is local variable in the function ChangeXto3() in the first code block..hence the answer 122 in the first code block.


这篇关于以下HTML / javascript代码中的一些混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆