从函数内改变全局变量 [英] Changing global Variable from within function

查看:143
本文介绍了从函数内改变全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我已经写下了这个非常简单的脚本,有点问题。这个脚本的目的是每次点击按钮时将给定的数字减一。我似乎无法做到这一点..我的全局变量是数字= 100似乎并没有改变,或改变多次..道歉无法解释这一点。
这里是正在处理的部分..:

 < script> 
var Number = 100; //数字我想要改变,并不断改变每个按钮点击
function outcome(){// Button调用这个函数
Number = Number - 1; //尝试更改全局编号..:/
}
document.write(Number); //将数字写入文档
< / script>


解决方案

是的,从概念上讲,这是正确的。只有你没有调用函数,至少在写 Number 到文档之前是没有的。



顺便说一句, Number 是全局引用 Number 构造函数,所以您应该使用另一个变量名称,最好是小写。

  var num = 100; 
函数结果(){
num--;
}
结果();
document.write(num); // 99

 <脚本> 
var num = 100;
函数结果(){
num--;
alert(num);
}
< / script>
< button onclick =outcome()>减少!< / button> b


$ >在jsfiddle.net上的演示)


Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well. Here is the part im working on..:

<script>
  var Number = 100;        // Number i want changed and to keep changing each button click
  function outcome() {     // Button calls this function
    Number = Number - 1;   // Tries to change Global Number.. :/
  }
  document.write(Number);  // Has the Number written in the document
</script> 

解决方案

Yes, conceptually this is right. Only you are not calling the function, at least not before writing Number to the document.

Btw, Number is the global reference to the Number constructor so you should use another variable name, lowercase at best.

var num = 100;
function outcome() {
    num--;
}
outcome();
document.write(num); // 99

or

<script>
var num = 100;
function outcome() {
    num--;
    alert(num);
}
</script>
<button onclick="outcome()">Decrease!</button>

(Demo at jsfiddle.net)

这篇关于从函数内改变全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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