繁体   English   中英

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

[英]Having issues with Array Splice with for loop

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

暂无
暂无

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

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