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!

Tomas Pastircak
  • 2,867
  • 16
  • 28
  • 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. – Ry- Apr 24 '14 at 14:59

1 Answers1

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.

David Thomas
  • 249,100
  • 51
  • 377
  • 410