全局和局部变量JavaScript

磁头

如何从函数外部获取函数内部的信息

var x = 0;

function myFunction() {  
    x += 1 //When a button is clicked Javascript will add 1 to x, now x will have a value of 1

}

alert(x) //This returns 0, how to make it return 1

PS仅纯JavaScript
PPS尝试简化您的答案,而无需编写大量代码。谢谢 :)

克里斯托斯(Christos)

它应该被称为myFunctionmyFunction()首先警报之前。这就是为什么得到0的原因。加载此脚本时,x的值为0。因此,警报将发出0警报。然后,每当用户单击您所引用的按钮时,的值x将增加1。话虽如此,我认为您需要这样的东西:

function myFunction() {
    // when the button will be clicked the value of x
    // would be incremented by one.  
    x += 1 

    // the new value would be alerted.
    alert(x);
}

另一种方式是这样的:

myFunction();
alert(x);

但是,这没有任何意义,因为您需要在x每次单击按钮时增加值,而无需强制执行myFunction

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章