0
 var a1 = new Array();
 var a2 = new Array();

function x() {
   for(var i = 1; i<=2; i++) {
       var number = document.getElementById("number" + [i]);
       a[i].push(number.value);
   }
}

a[i].push(number.value); is what I want to do but it doesn't work. It would be best if wouldn't have to change the entire code I'm working on, but any solutions will be much appericiated. Thanks in advance!

1
  • Note that you should use the object as suggested by the answer to this question and the second part of the accepted answer to the duplicate. Commented Apr 24, 2014 at 14:59

1 Answer 1

1

I'd suggest a small rewrite:

var arrays = {
        '1' : [],
        '2' : []
    };

function x() {
    for(var i = 1; i<=2; i++) {
        var number = document.getElementById("number" + [i]);
        arrays[i].push(number.value);
    }
}

The problem you were having, I think, is that JavaScript doesn't concatenate the 'a' with the i variable to form the variable-name; this approach stores both arrays in the same object and uses the numbers as keys within that object.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.