我正在制作一种琐碎的追击游戏。我有成千上万的问题和答案;见下面的例子:
var trivialPursuitCards = [
{
question: "What nationality was Chopin?",
answer: ["American", "Polish", "German", "Czech"],
difficulty: 2
},
{
question: "Who cut Van Gogh's ear?",
answer: ["His sister", "His brother", "Himself", "He was born that way"],
difficulty: 2
}
];
现在我只需要为每张卡添加一个属性,即:rightAnswer: undefined
。
为所有卡片完成此操作的最佳方法是什么?
答案 0 :(得分:2)
for(var i=0; i<trivialPursuitCards.length; i++) {
trivialPursuitCards[i].rightAnswer = undefined;
}
答案 1 :(得分:1)
使用var trivialPursuitCards = [{
question: "What nationality was Chopin?",
answer: ["American", "Polish", "German", "Czech"],
difficulty: 2
}, {
question: "Who cut Van Gogh's ear?",
answer: ["His sister", "His brother", "Himself", "He was born that way"],
difficulty: 2
}];
var update = trivialPursuitCards.map(function(e, i) {
e.rightAnswer = undefined;
return e;
});
console.log(update);
然后添加您的媒体资源: -
{{1}}&#13;
答案 2 :(得分:0)
trivialPursuitCards.map(function (card) { card.rightAnswer = null; });
因为添加null
而不是undefined
因为rightAnswer
应该存在,但目前尚未设置,所以
答案 3 :(得分:0)
正如Juhana所指出的那样:
默认情况下,不存在未定义的属性,因此您似乎不太可能需要明确设置它。
但是,如果您真的想这样做,可以使用Array.prototype.map()
:
trivialPursuitCards = trivialPursuitCards.map(element=>
element.rightAnswer = undefined
)