使用for循环遇到Array Splice的问题

时间:2014-06-10 08:14:06

标签: 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);
    }
}

2 个答案:

答案 0 :(得分:4)

当您在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);
    }
}

此外,无需对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;
});

答案 1 :(得分:0)

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

var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];

var result = questions.filter(function(e) {
  return answeredQuestions.indexOf(+e.questionid) == -1;
});