Javascript Global Variable in Array
- by user1387727
My question may be very easy to lots of people, but I am new to Javascript. I really do not know what is wrong with the following codes.
var newValue = 1;
function getCurrentAmount() {
return [newValue,2,3];
}
var result = getCurrentAmount();
console.log(result[0] + "" + result[1] + result[2]);
In the above code, the result shown in console is: undefined23
Why is the result not "123"? I am trying to use global variable because I want to increment newValue by 1 each time when the function is called.
I want something like the following:
var newValue = 1;
function getCurrentAmount() {
newValue ++;
return [newValue,2,3];
}
setInterval(function(){
var result = getCurrentAmount();
console.log(result[0] + "" + result[1] + result[2]);
}, 1000);
Also, I just tired the following codes and it works as expected.
var newValue =1;
function test() {
newValue ++;
return newValue;
}
console.log(test());
So I think the problem is about the Array.
I hope my question is clear enough. Thanks in advance.