上面的代码只拼接第一个元素它在for循环中第二次不起作用!请帮忙!
var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];
for (var j = 0; j < questions.length; j++) {
var pos = $.inArray(parseInt(questions[j].questionid), answeredQuestions);
if(parseInt(pos) != -1) {
questions.splice(j,1);
}
}
最佳答案
当您在 for
循环中间修改数组(从中删除项目)时,它会导致您的 for
循环丢失数组中的项目。
一种解决方法是向后处理数组(从头到尾),这样当您从数组中删除当前项时,您就不会在下一次迭代中弄乱任何索引for
循环。
var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];
for (var j = questions.length - 1; j >= 0; j--) {
var pos = $.inArray(parseInt(questions[j].questionid, 10), answeredQuestions);
if(pos !== -1) {
questions.splice(j,1);
}
}
此外,无需对 $.inArray
的结果使用 parseInt()
,因为它已经是一个整数。
自 2015/2016 起编辑,使用 .filter()
并让该方法为您处理数组的修改可能更容易:
var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];
questions = questions.filter(function(item) {
// keep only questions that haven't been answered already
return answeredQuestions.indexOf(+item.questionid) === -1;
});
关于javascript - 带有 for 循环的 Array Splice 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136019/