gpt4 book ai didi

通过for循环的javascript数组格式

转载 作者:行者123 更新时间:2023-11-28 00:39:05 26 4
gpt4 key购买 nike

我在这里做错了什么?我收到 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);

关于通过for循环的javascript数组格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28140217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com