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

Add property to each object in the array

本文关键字:对象 数组 属性 添加      更新时间:2024-01-19

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

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
}];

应该变成:

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
    }];

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

您必须在此上下文中使用forEach

capitals.forEach(function(itm){
 itm.global = true;
});

如果您不熟悉forEach的用法,那么您可以通过使用for循环来完成同样的工作。

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

如果不必支持旧版浏览器,则可以使用Array.prototype.map