我正在检查一组文本条目,看它们是否符合邮政编码格式。这是我的代码:
var invZIPs;
ZIP.forEach(function(z, i) {
console.log(z);
console.log(ZIP);
if(!isZIP(z)){
invZIPs += "(" + z + ")";
ZIP.splice(i,1);
}
console.log(ZIP);
});
if(invZIPs != ""){
console.log(""Ignored unrecognized entries: " + invZIPs");
}
为了调试,我在检查前后打印了 forEach 条目和数组。这是我的输出。
1
["1", "2", "31833", "4", "5"]
["2", "31833", "4", "5"]
31833
["2", "31833", "4", "5"]
["2", "31833", "4", "5"]
4
["2", "31833", "4", "5"]
["2", "31833", "5"]
为什么它不检查某些条目?
最佳答案
Why is it not checking some entries?
将被访问的元素范围在回调循环开始之前确定,并且即使您删除正在访问的条目也会继续下一个元素。 (参见 the spec 。)因此,如果您在迭代期间修改数组,您将获得奇怪的效果。例如,假设条目 0
无效;您将其删除,使条目 1
条目 0
、条目 2
条目 1
等;然后循环继续进入条目 1
并且永远不会检查(新)条目 0
。
Array#filter
在这种情况下可能是更好的选择。
ZIP = ZIP.filter(function(z, i) { // Note we're assigning the new array
console.log(z);
console.log(ZIP);
if(!isZIP(z)){
invZIPs += "(" + z + ")";
return false; // Leave it out of the result
}
console.log(ZIP);
return true; // Include it in the result
});
旁注:您也永远不会给 invZIPs
一个初始值。从你对 +=
的使用来看,你可能想要
var invZIPs = "";
关于javascript - ForEach 在 Javascript 中跳过条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556002/