javascript 声明对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15742442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:56:31  来源:igfitidea点击:

Declaring array of objects

javascriptarraysobjectdeclare

提问by Prasath K

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?

我尝试了上面的代码,但它不起作用。如何在不使用索引号的情况下初始化对象数组?

回答by Daniel Imms

Use array.push()to add an item to the end of the array.

使用array.push()将项目添加到数组的结尾。

var sample = new Array();
sample.push(new Object());

To do this ntimes use a forloop.

为此,请n使用for循环。

var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
    sample.push(new Object());


Note that you can also substitute new Array()with []and new Object()with {}so it becomes:

请注意,您也可以替换new Array()[]new Object(){}因此它变为:

var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
    sample.push({});

回答by Frédéric Hamidi

Depending on what you mean by declaring, you can try using object literalsin an array literal:

根据声明的含义,您可以尝试在数组文字中使用对象文字

var sample = [{}, {}, {} /*, ... */];

EDIT:If your goal is an array whose undefineditems are empty object literals by default, you can write a small utility function:

编辑:如果您的目标是一个数组,其undefined项目默认为空对象文字,您可以编写一个小的实用程序函数:

function getDefaultObjectAt(array, index)
{
    return array[index] = array[index] || {};
}

Then use it like this:

然后像这样使用它:

var sample = [];
var obj = getDefaultObjectAt(sample, 0);     // {} returned and stored at index 0.

Or even:

甚至:

getDefaultObjectAt(sample, 1).prop = "val";  // { prop: "val" } stored at index 1.

Of course, direct assignment to the return value of getDefaultObjectAt()will not work, so you cannot write:

当然,直接赋值给 的返回值是getDefaultObjectAt()不行的,所以不能这样写:

getDefaultObjectAt(sample, 2) = { prop: "val" };

回答by Ced

You can use fill().

您可以使用fill()

let arr = new Array(5).fill('lol');

let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));

Will create an array of 5 items. Then you can use forEach for example.

将创建一个包含 5 个项目的数组。然后你可以使用 forEach 例如。

arr.forEach(str => console.log(str));

Note that when doing new Array(5)it's just an object with length 5 and the array is empty. When you use fill()you fill each individual spot with whatever you want.

请注意,这样做时new Array(5)它只是一个长度为 5 的对象,并且数组为空。当您使用时,您可以用fill()您想要的任何东西填充每个单独的位置。

回答by Jeff Shaver

After seeing how you responded in the comments. It seems like it would be best to use pushas others have suggested. This way you don't need to know the indices, but you can still add to the array.

在看到你在评论中的回应后。似乎最好push按照其他人的建议使用。这样你就不需要知道索引,但你仍然可以添加到数组中。

var arr = [];
function funcInJsFile() {
    // Do Stuff
    var obj = {x: 54, y: 10};
    arr.push(obj);
}

In this case, every time you use that function, it will push a new object into the array.

在这种情况下,每次使用该函数时,它都会将一个新对象推送到数组中。

回答by Eric Jablow

You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use pushas Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.

你真的不需要创建 blank Objects。你不能对他们做任何事情。只需根据需要将您的工作对象添加到示例中。使用push丹尼尔IMMS建议,并使用文字作为弗雷德里克·哈米迪建议。您似乎想像 C 一样编写 Javascript。

var samples = []; /* If you have no data to put in yet. */
/* Later, probably in a callback method with computed data */
/* replacing the constants. */
samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
/* or */
samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */

I believe using new Array(10)creates an array with 10 undefinedelements.

我相信 usingnew Array(10)创建一个包含 10 个undefined元素的数组。

回答by MarzSocks

You can instantiate an array of "object type" in one line like this (just replace new Object()with your object):

您可以像这样在一行中实例化“对象类型”数组(只需将new Object()替换为您的对象):

var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });

回答by spitterfly

Well array.lengthshould do the trick or not? something like, i mean you don't need to know the index range if you just read it..

那么array.length应该做的伎俩或不?就像,我的意思是,如果你只是阅读它,你就不需要知道索引范围..

var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
    arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}

Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.

也许我没有正确理解您的问题,但是您应该能够通过这种方式获得数组的长度并将它们转换为对象。老实说,丹尼尔也给出了同样的答案。您可以将数组长度保存到他的变量中,然后就可以了。

IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:

如果我认为这不应该发生,您将无法获得数组长度。正如您所说,无需获取索引号,您可以这样做:

var arrayContainingObjects = [];
for (;;){
    try{
        arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
    }
}
catch(err){
    break;
}

It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.

这是上面那个版本的不好的版本,但是循环会一直执行,直到您“跑”出索引范围。

回答by ShuklaSannidhya

Try this-

试试这个-

var arr = [];
arr.push({});

回答by Abdallah Okasha

//making array of book object
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []    
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name); 

console.log(my_albums[0].name);
console.log(my_albums[1].name); 

This Example Works with me. Snapshot for the Output on Browser Console

这个例子对我有用。 浏览器控制台输出的快照

回答by ashishdudhat

Use array.push() to add an item to the end of the array.

使用 array.push() 将一个项目添加到数组的末尾。

var sample = new Array();
sample.push(new Object());

you can use it

你可以使用它

var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
  sample.push({}) 
  OR
  sample.push(new Object())
}