Changing global Variable from within function

谁说胖子不能爱 提交于 2020-01-03 15:56:54

问题


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> 

回答1:


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)




回答2:


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> 


来源:https://stackoverflow.com/questions/15604177/changing-global-variable-from-within-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!