javascript 如何将动态对象推入数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12979121/
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-26 17:32:27  来源:igfitidea点击:

How can I push a dynamic object into array?

javascriptarraysobjectloopsdynamic

提问by Dan

Possible Duplicate:
Javascript expression to define object's property name?

可能的重复:
用于定义对象属性名称的 Javascript 表达式?

I'm trying to add objects to an array, but I want to have the name and value to be dynamic. Here's an example:

我正在尝试将对象添加到数组中,但我希望名称和值是动态的。下面是一个例子:

    (function(){
        var data = [];

        for(i=0; i<5; i++){
            data.push({'name' + i: i});
    }

        console.log(data);
    })()

I guess I can't use a variable for the property so I'm not sure what to do.

我想我不能为该属性使用变量,所以我不知道该怎么做。

回答by zzzzBov

If you want to use a dynamically named property, you need to use array access notation:

如果要使用动态命名的属性,则需要使用数组访问符号:

var temp = {};
temp['name' + i] = i;
data.push(temp);
In the IIFE:在 IIFE 中:
(function(){
    var data,
        temp,
        i;
    data = [];
    for (i = 0; i < 5; i += 1) {
        temp = {};
        temp['name' + i] = i;
        data.push(temp);
    }
    console.log(data);
}());

回答by Anoop

Modified code: key based on variable value can be added in an object using '[]'. jsfiddle

修改代码:可以使用'[]'将基于变量值的键添加到对象中。提琴手

 (function(){
        var data = [], a;

        for(i=0; i<5; i++){
             a = {};
             a['name' + i] = i;
            data.push(a);
    }

        console.log(data);
    })()

回答by I Hate Lazy

Like this:

像这样:

for(i=0; i<5; i++){
    var obj = {};
    obj["name" + i] = i;
    data.push(obj);
}

But I would wonder why you'd want to hard-code the index into the property name.

但我想知道为什么您要将索引硬编码到属性名称中。

Since you have an Array, you already have an associated index. It also makes the property hard to look up.

因为你有一个数组,你已经有了一个关联的索引。这也使财产难以查找。

If you need an association of the original index, I'd use a separate property.

如果您需要原始索引的关联,我会使用单独的属性。

for(i=0; i<5; i++){
    data.push({name: i, idx: i});
}