0

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.

1
  • Did you try to set elem2 to be array()? Commented Oct 28, 2010 at 13:46

3 Answers 3

2

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.

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.