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
Solution 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;
functionoutcome() {
num--;
}
outcome();
document.write(num); // 99
or
<script>var num = 100;
functionoutcome() {
num--;
alert(num);
}
</script><buttononclick="outcome()">Decrease!</button>
Solution 2:
You have to call your function:
<script>varNumber=100functionoutcome(){
Number=Number-1
}
outcome(); // call the function heredocument.write(Number)
</script>
or don't use a function in the first place:
<script>varNumber=100Number=Number-1document.write(Number)
</script>
Post a Comment for "Changing Global Variable From Within Function"