javascript 通过 for 循环的数组格式
javascript array format via for loop
我这里做错了什么?我收到 TypeError: items[i] is undefined
作为错误。
var items = [];
for(var i = 1; i <= 3; i++){
items[i].push('a', 'b', 'c');
}
console.log(items);
我需要如下所示的输出,
[
['a', 'b', 'c'],
['a', 'b', 'c'],
['a', 'b', 'c']
]
您可以简单地使用以下内容:
items.push(['a', 'b', 'c']);
无需使用索引访问数组,只需将另一个数组推入即可。
.push()
方法会自动将其添加到数组的端。
var items = [];
for(var i = 1; i <= 3; i++){
items.push(['a', 'b', 'c']);
}
console.log(items);
作为旁注,值得指出的是以下内容会起作用:
var items = [];
for(var i = 1; i <= 3; i++){
items[i] = []; // Define the array so that you aren't pushing to an undefined object.
items[i].push('a', 'b', 'c');
}
console.log(items);
我这里做错了什么?我收到 TypeError: items[i] is undefined
作为错误。
var items = [];
for(var i = 1; i <= 3; i++){
items[i].push('a', 'b', 'c');
}
console.log(items);
我需要如下所示的输出,
[
['a', 'b', 'c'],
['a', 'b', 'c'],
['a', 'b', 'c']
]
您可以简单地使用以下内容:
items.push(['a', 'b', 'c']);
无需使用索引访问数组,只需将另一个数组推入即可。
.push()
方法会自动将其添加到数组的端。
var items = [];
for(var i = 1; i <= 3; i++){
items.push(['a', 'b', 'c']);
}
console.log(items);
作为旁注,值得指出的是以下内容会起作用:
var items = [];
for(var i = 1; i <= 3; i++){
items[i] = []; // Define the array so that you aren't pushing to an undefined object.
items[i].push('a', 'b', 'c');
}
console.log(items);