var answersAll=[]; answersAll[0]={ "id":"1111", "questionType":3, "answerContent":["题1"] } answersAll[1]= { "id":"2222", "questionType":3, "answerContent":["题2"] } answersAll[2]= { "id":"3333", "questionType":3, "answerContent":["题3"] } answersAll[3]= { "id":"4444", "questionType":3, "answerContent":["题4"] }
answersAll[4]= { "id":"kkkk", "questionType":3, "answerContent":["题5"] }
var answers=[]; answers[0]={ "id":"4444", "questionType":3, "answerContent":["侧是是是是是是佛山市"] }
for(var i=0;i<answersAll.length;i++){ //如果相等,說明id重複,覆蓋之 if(answersAll[i].id===answers[0].id){ console.log("要删的位置"+i); //覆盖 answersAll.splice(i,1,answers[0]); //删掉后面多余题 answersAll=(answersAll.slice(0,i+1));
coverFlag=true;
}
}
console.log(JSON.stringify(answersAll));
//判断一下,若不改题,id不重复,则添加; 改题,id重复,则覆盖, 并删掉后面多余题 let answersAllHasIdFlag = findElem(answersAll, 'id', answers[0].id);
if(answersAllHasIdFlag == -1){ answersAll=answersAll.concat(answers); }else if(answersAllHasIdFlag != -1){ //覆盖 answersAll.splice(answersAllHasIdFlag,1,answers[0]); //删掉后面多余题 answersAll=(answersAll.slice(0,answersAllHasIdFlag+1)); }
//找到对象数组的 特定下标值,并返回下标 function findElem(array, attr, val) { for (var i = 0; i < array.length; i++) { if (array[i][attr] == val) { return i; //返回当前索引值 } } return -1; };