简体   繁体   English

从函数内改变全局变量

[英]Changing global Variable from within function

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. 我似乎无法做到这一点。我的全局变量是数字= 100似乎没有变化,或改变不止一次..抱歉无法解释这一点。 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. 只有您没有调用该函数,至少在将Number写入文档之前。

Btw, Number is the global reference to the Number constructor so you should use another variable name, lowercase at best. 顺便说一下, NumberNumber构造函数的全局引用,所以你应该使用另一个变量名,最好是小写。

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 ) 在jsfiddle.net上演示

You have to call your function: 你必须打电话给你的功能:

<script>
var Number=100    
function outcome(){ 
Number=Number-1 
}
outcome(); // call the function here
document.write(Number)  
</script> 

or don't use a function in the first place: 或者首先不要使用函数:

<script>
var Number=100    
Number=Number-1   
document.write(Number) 
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM