使用 for 循环进行 Array Splice 的问题

Shr*_*awa 4 javascript json

上面的代码只拼接第一个元素,它在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 5

当您在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,没有必要parseInt()在结果上使用,$.inArray因为它已经是一个整数。


从 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;
});
Run Code Online (Sandbox Code Playgroud)