我有一个基于问题数组预先填充长度的答案数组
$scope.length = parseInt($scope.questions.length);
$scope.quizAnswers = [];
for(var i = 0 ; i < parseInt($scope.length) ; i++)
$scope.quizAnswers.push({id:i, Index:i, Answered":"No","Correct":"null"});
我希望将此答案数组中的对象替换为其索引值 根据答案
quizAnswers: [{"id":0,"Index":0,"Answered":"No","Correct":"null"},{"id":1,"Index":1,"Answered":"No","Correct":"null"},{"id":3,"Index":3,"Answered":"No","Correct":"null"},{"id":0,"Index":2,"Answered":"Yes","Correct":"Correct"}]
所以最终的对象{"id":0,"Index":2,"Answered":"Yes","Correct":"Correct"}
需要替换{"id":2,"Index":2,"Answered":"No","Correct":"null"}
,有没有办法通过推送或拼接到数组
答案 0 :(得分:2)
数组基于索引。所以这意味着您可以通过索引
访问该值quizAnswers = [
{"id":0,"Answered":"No","Correct":"null"},
{"id":1,"Answered":"No","Correct":"null"},
{"id":3,"Answered":"No","Correct":"null"},
{"id":0,"Answered":"Yes","Correct":"Correct"}
];
quizAnswers[2] = {"id":2,"Answered":"Yes","Correct":"Correct"};
答案 1 :(得分:1)
将答案作为对象而不是数组可能更容易。然后,您可以使用索引作为键。例如:
quizAnswers = {
"0": {"id":0,"Answered":"No","Correct":"null"},
"1": {"id":1,"Answered":"No","Correct":"null"},
"3": {"id":3,"Answered":"No","Correct":"null"},
"2": {"id":0,"Answered":"Yes","Correct":"Correct"}
}
这将允许您直接更新答案。例如:
quizAnswers["2"] = {"id":0,"Answered":"Yes","Correct":"Correct"};