我创建了一个数组:
var test = new Array(5);
for (i=0; i<=5; i++)
{
test[i]=new Array(10);
}
现在我想向字段中添加对象:
test[0][5].push(object);
但是出现错误:
Uncaught TypeError: Cannot call method 'push' of undefined
我使用“推”是因为我想在此字段中放入 0-4 个对象,但我不知道到底有多少对象。 我应该如何更改它以使其正确?
最佳答案
表达式 test[0]
指的是一个新的 Array 实例,由以下行创建:
test[i]=new Array(10);
但是,该数组 中没有任何内容。因此,test[0][5]
指的是一个 undefined object 。您需要先将 that 初始化为一个数组,然后才能向其push()
某些内容。例如:
test[0][5] = []; // Set [0][5] to new empty array
test[0][5].push(object); // Push object onto that array
甚至:
test[0][5] = [object]; // Set [0][5] to one item array with object
关于javascript - 二维数组 - 将对象添加到字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15395455/