Javascript拼接在jQuery .each()上中断了吗? [英] Javascript splice is breaking on jQuery .each()?
问题描述
var results = ['one', 'two', 'one hundred', 'three'];
var removal = [];
$.each(results, function(i) {
removal.push(i);
if (results[i].indexOf('one') == -1){
console.log('Removing:' + results[i] + '(' + removal[i] + ')');
results = results.splice(removal[i], 1);
}
});
我有以下代码,但是删除第一个结果后,它就中断了.
I have the following code, but it is breaking after it removes the first result.
我希望它删除不包含"one"一词的所有内容.
I want it to remove anything that does not contain the word 'one'.
我想这很麻烦,因为一旦删除顺序,删除顺序就会更改.
I am guessing it is breaking because the removal order changes once one has been removed.
我在做什么错了?
推荐答案
在使用$.each()
进行迭代时,不应拼接数组.
You shouldn't splice the Array while you're iterating it with $.each()
.
由于您要更改数组的长度,因此您将超出最终索引.
Since you're changing the length of the Array, you're going beyond the final index since.
只需使用for
循环并在删除项目时调整i
...
Just use a for
loop and adjust i
when you remove an item...
var results = ['one', 'two', 'one hundred', 'three'];
var removal = [];
for(var i = 0; i < results.length; i++) {
removal.push(i);
if (results[i].indexOf('one') == -1){
console.log('Removing:' + results[i] + '(' + removal[i] + ')');
results.splice(i, 1);
i--;
}
};
请注意,我已对此进行了更改...
Note that I changed this...
results = results.splice(removal[i], 1);
对此...
results.splice(removal[i], 1);
您不希望这样做,因为splice()
会修改原始文件并返回被删除的项目.
You don't want that since splice()
modifies the original, and returns the item(s) removed.
这篇关于Javascript拼接在jQuery .each()上中断了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!