javascript - 二维数组 - 将对象添加到字段

标签 javascript arrays

我创建了一个数组:

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/

相关文章:

javascript - Flexbox 强制滚动到底部

javascript - 尽管 Javascript 中有默认参数,如何传递额外参数?

javascript - 替换嵌套元素中的 css 类

javascript - 数组内具有特定属性的 polymer 计数元素

arrays - Array.isDefinedAt 用于 scala 中的 n 维数组

javascript - 检查多个字符串以匹配多个正则表达式(均为数组)

单个类类型的 C# 数组或列表

python - Numpy 距阵列中心的平均距离

javascript - Angular Directive(指令)的行为不符合预期。我需要一些帮助来找出原因

javascript - Google Maps API 不在 DIV 标记内呈现