简体   繁体   English

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

[英]Having issues with Array Splice with for loop

Above code splices only first element it doesn't work second time in for loop! 上面的代码仅拼接第一个元素,它在for循环中第二次不起作用! Please help! 请帮忙!

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);
    }
}

When you modify the array (remove items from it) in the middle of the for loop, it causes your for loop to miss items in the array. 当您在for循环的中间修改数组(从中删除项目)时,它会导致for循环错过数组中的项目。

One way to work-around that is to process the array backwards (from end to front) so that when you remove the current item from the array, you aren't messing up any of the indexes in the next iterations of the for loop. 解决方法的一种方法是向后处理数组(从头到尾),这样当你从数组中删除当前项时,你就不会在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);
    }
}

Also, there is no need to use parseInt() on the result of $.inArray as it is already an integer. 此外,没有必要对$.inArray的结果使用parseInt() ,因为它已经是一个整数。


Edit as of 2015/2016 , it's probably easier to use .filter() and let that method handle the modifying of the array for you: 编辑截至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;
});

What you want to do is just filter the answered questions. 你想要做的只是过滤回答的问题。 You could use .filter : 你可以使用.filter

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM