views:

37

answers:

3

I have an array:

myArray = [];

To which I am adding objects:

data = [];

myArray.push( {
  elem1: ...,
  elem2: data.push(...);
} );

So, elem2 in the object contains an array. How can I, given myArray add new elements to the array in elem2? I tried the following:

myArray[idx].elem2.push("new data");

But got an error saying that elem2.push() is not a method.

A: 

The .push() function does not return the array, so that line that tries to set "elem2", well it isn't doing that.

Pointy
+2  A: 

The issue line is:

elem2: data.push(...)

data is an array. The push method for arrays does not return the array, it returns the length of the array once the item has been added.

So if you have:

var data = [];

var moreData = data.push(1);

moreData will actually equal 1.

Since the value of elem2 is actually an integer, you are then calling push on that integer. That's where you are getting the error.

TreyE
A: 

I tried the same and works, look the code:

var a = [];
a.push({

  a: []

});

a[0].a.push("a");

alert(a[0].a[0]); // return 'a'

in your array you must add another array, not the array.push(), because it will return the position that elements was inserted.

madeinstefano