有问题的数组拼接与for循环

Having issues with Array Splice with for loop

本文关键字:for 循环 拼接 数组 有问题      更新时间:2023-09-26

上面的代码只拼接了第一个元素,在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;
});

您要做的就是过滤已回答的问题。您可以使用.filter:

var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];
var result = questions.filter(function(e) {
  return answeredQuestions.indexOf(+e.questionid) == -1;
});