Foreach & add remove elements

参考
http://stackoverflow.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就会被忽略

posted @ 2015-08-16 17:14  cart55free99  阅读(142)  评论(0编辑  收藏  举报