问题描述
我有一个变量,它是一个数组,我希望数组的每个元素默认都充当一个对象.为了实现这一点,我可以在我的代码中做这样的事情.
I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.
var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();
这很好用,但我不想提及任何索引号.我希望我的数组的所有元素都是一个对象.我如何声明或初始化它?
This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?
var sample = new Array();
sample[] = new Object();
我尝试了上面的代码,但它不起作用.如何在不使用索引号的情况下初始化对象数组?
I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?
推荐答案
使用 array.push()
将一项添加到数组的末尾.
Use array.push()
to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
要做到这一点 n
次,请使用 for
循环.
To do this n
times use a for
loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
请注意,您还可以将 new Array()
替换为 []
并将 new Object()
替换为 {}所以它变成:
Note that you can also substitute
new Array()
with []
and new Object()
with {}
so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
这篇关于声明对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!