javascript object操作
一個來自 http://www.codewars.com/ 小小記錄
問題:有一個 陣列物件 var questions =
[{ question: "What's the currency of the USA?", choices: ["US dollar", "Ruble", "Horses", "Gold"], corAnswer: 0 },
{ question: "Where was the American Declaration of Independence signed?", choices: ["Philadelphia", "At the bottom", "Frankie's Pub", "China"], corAnswer: 0 }];
以上若是要增加一個 陣列元素增加一個屬性usersAnswer 並將值設成null
作法一:
questions.forEach(function(obj){
obj.usersAnswer = null;
});
作法二:
for(var i =0;i<questions.length;i++){
questions[i].usersAnswer = null;
}
這樣就可以快速新增陣列元素物件的屬性了...看來方法一簡潔很多..(要趕快習慣這種寫法阿@@)
p.s. 補充一下 若要刪除元素 只需要 delete 物件.屬性 就可以嚕...很方便吧