gpt4 book ai didi

javascript - 如何从javascript中的foreach循环中删除特定的数组元素

转载 作者:数据小太阳 更新时间:2023-10-29 03:58:27 28 4
gpt4 key购买 nike

var fruit = ["apple","pear","pear","pear","banana"];

如何从这个数组中删除所有“梨”水果?
我尝试了以下方法,但仍然剩下一个梨:

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

我做错了什么?现场演示:http://jsfiddle.net/SbxHc/

最佳答案

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"]

关于javascript - 如何从javascript中的foreach循环中删除特定的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058384/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com