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)
该数组可以包含多个对象.我需要什么样的功能?
你必须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)
归档时间: |
|
查看次数: |
4400 次 |
最近记录: |