Foreach & add remove elements

参考

http://*.com/questions/11058384/how-to-delete-specific-array-elements-from-within-a-foreach-loop-in-javascript

https://gist.github.com/chad3814/2924672

for(var f in fruit) {
if ( fruit[f] == "pear" ) {
fruit.splice(f, 1);
}
} for(var f in fruit) {
document.write(fruit[f]+"<br>");
} //
apple
pear
banana

you should handle it in this way

var fruit = ["apple", "pear", "pear", "pear", "banana"],
i; for (i = 0; i < fruit.length; ++i) {
if (fruit[i] === "pear") {
fruit.splice(i--, 1);
}
} console.log(fruit);
//["apple", "banana"]

原理很显然

当我删除第一个pear的时候 数组是apple pear pear banna

此时继续遍历 将从[2]下标开始 有一个pear就会被忽略

上一篇:[转载]CentOS 7安装Gnome GUI 图形界面


下一篇:CF1131D tarjan,拓扑