Skip to content Skip to sidebar Skip to footer

Array[key].push Is Not Defined In Javascript

When trying to push items to an array in javascripts it gives an error, the following pseudo code illustrate what is happening: var data = new Array(); for(...) { data[key].pu

Solution 1:

If you need a 2d array, you have to initialize each element of the outer array to be an array.

// Have to check every array item, if it's not an array already, make it sofor(...) {
    if (!data[key]) {
        data[key] = [];
    }
    data[key].push(item[i]);
}

You could always do the following if you know the number of inner arrays you need:

var data = [[],[],[],[],[],[]];

In your example, since they variable name is key, I'm assuming you actually want an object of arrays. If you know the keys ahead of time, you can use the following literal.

vardata = {
  myKey1: [],
  myKey2: []
}

Post a Comment for "Array[key].push Is Not Defined In Javascript"