Javascript Global Variable in Array

Posted by user1387727 on Stack Overflow See other posts from Stack Overflow or by user1387727
Published on 2012-11-28T16:55:21Z Indexed on 2012/11/28 17:04 UTC
Read the original article Hit count: 154

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about arrays