1

I created an array:

var test = new Array(5);
for (i=0; i<=5; i++)
{
 test[i]=new Array(10);
}

And now i want to add object to the field:

test[0][5].push(object);

But appears an error:

Uncaught TypeError: Cannot call method 'push' of undefined

I'm using "push" because I want to put into this field 0-4 objects but I don't know exactly how many object will be there. How should I change it to make it correct?

2
  • 3
    The reason you're getting the error is because test[0][5] is returning undefined (since there is nothing in the array living at test[0]) and calling push on it. I'm not sure I understand what you mean by "I want to put into this field 0-4 objects, but I don't know exactly how many objects will be there". Commented Mar 13, 2013 at 20:12
  • in one field can be from 0 to 4 objects Commented Mar 13, 2013 at 20:42

5 Answers 5

5

The expression test[0] refers to a new Array instance, created by the line:

test[i]=new Array(10);

However, there's nothing in that array. Thus, test[0][5] refers to an undefined object. You'll need to initialize that to an array before you can push() something on to it. For example:

test[0][5] = []; // Set [0][5] to new empty array
test[0][5].push(object); // Push object onto that array

Or even:

test[0][5] = [object]; // Set [0][5] to one item array with object
Sign up to request clarification or add additional context in comments.

2 Comments

but this objects will be added while the app is running. I can't clear this array.
Then after you set test[i] to a new array, loop through that array and set each index to an empty array.
2
var test = new Array(5);
for (i=0; i<=5; i++)
{
  test[i]=new Array();
}

this will let you create a multi-dimensional array. Each element in the variable test will be an array.

From here you can do

test[0].push("push string");
test[0].push("push string2");

from here

test[0][1] will contain "push string2"

Comments

1

Change "<=" to "<".

for (i = 0; i < 5; i++)

Arrays are zero based so if you have an array with 5 slots and you want to access the last slot you would use:

anArray[4]

1 Comment

Yeah you're right. There were too many things wrong here when I first looked at it.
0

before use push ask to value is an array

if(test[0][5] instanceof  Array)
    test[0][5].push(object);

Comments

0
test[0][5] = new Array(); // you need initialize this position in Array
test[0][5].push(object); // and then push object

or

test[0][5] = [object]; // directly create a new Array with object

but if you just want to have an object in this position, you should do it:

test[0][5] = object;

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.