将属性添加到数组中的每个对象

Sca*_*ola 0 javascript arrays object

我正在尝试向数组中的每个对象添加一个属性:

var capitals = [{
    country: "What's the capital of Ecuador?",
    choices: ["Quito", "Caracas", "Panama", "Loja"],
    corAnswer: 0
}, {
    country: "What is the capital of China?",
    choices: ["Shanghai", "Beijing", "Ghangzou", "Hong Kong"],
    corAnswer: 0
}];
Run Code Online (Sandbox Code Playgroud)

应该成为:

var capitals = [{
        country: "What's the capital of Ecuador?",
        choices: ["Quito", "Caracas", "Panama", "Loja"],
        corAnswer: 0,
        global: true
    }, {
        country: "What is the capital of China?",
        choices: ["Shanghai", "Beijing", "Ghangzou", "Hong Kong"],
        corAnswer: 0,
        global: true
    }];
Run Code Online (Sandbox Code Playgroud)

该数组可以包含多个对象.我需要什么样的功能?

Raj*_*amy 7

你必须forEach在这种情况下使用,

capitals.forEach(function(itm){
 itm.global = true;
});
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉其用法forEach,则可以使用for循环执行相同的工作.

for(var i=0,len=capitals.length;i<len;i++){
  capitals[i].global = true;
}
Run Code Online (Sandbox Code Playgroud)

  • `const capital = [{}, ...].map(i =&gt; { i.global = true; return i; })` 就是这样 (2认同)