本文介绍了函数,全局变量和局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白为什么测试后的x不会变成30但仍然保持10
I can't understand why the x after test won't become 30 but still remains 10
<script>
function test(){
var x = 30;
y = 40;
}
</script>
<script>
var x = 10;
var y = 20;
document.write("before test, x: " + x + ", y: " + y + "<br/><br/>");
test();
document.write("after test, x: " + x + ", y: " + y + "<br/><br/>");
</script>
推荐答案
这是因为通过声明 var x = 30;
,您创建了一个名为 x
的变量
This is because by declaring var x = 30;
, you create a variable named x
that exists only in the function's scope.
但是,变量 y
仅在顶层定义.因此,当您运行函数 test
时,您将编辑本地 x
变量和全局(顶级)y y
变量.
The variable y
, however, is only defined at top-level. So when you run the function test
, you edit the local x
variable, and the global (top-level) y
variable.
这篇关于函数,全局变量和局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!