简体   繁体   English

为什么我不能从数组中删除元素?

[英]Why can't I remove elements from the array?

This function should remove elements that are less than 1 and more than 4, but it doesn't.这个 function 应该删除小于 1 和大于 4 的元素,但它没有。 The array is still the same.数组还是一样的。

 let arr = [5, 3, 8, 1]; function filterRangeInPlace(arr, a, b) { arr.forEach((item, index) => { if (a > item && b < item) { arr.splice(index, 1); }; }); }; filterRangeInPlace(arr, 1, 4); console.log(arr);

What's wrong?怎么了?

When would an individual item be both less than 1 and more than 4?什么时候单个项目既小于 1 又大于 4? If you want to remove items that are less than 1 or more than 4 you need to do:如果要删除小于 1大于 4 的项,则需要执行以下操作:

if (a > item || b < item)

you are inverting the arguments when calling the function. you should rather do你在调用 function 时反转了 arguments。你应该这样做

 filterRangeInPlace(arr, 4, 1)

you are basically keeping items between given range instead removing items go for keeping items this will return same also use filter function it basically iterate through array and just like foreach there are two parameters inside it item and index the only difference is filter keeps value when you return true or ignore if you return false您基本上是将项目保持在给定范围之间,而不是删除项目 go 以保持项目这将返回相同的也使用filter function 它基本上遍历数组,就像foreach里面有两个参数 item 和 index 唯一的区别是过滤器在您时保留值如果返回 false,则返回 true 或忽略

you can check more about filter here filter您可以在此处查看有关过滤器的更多信息

 let arr = [5, 3, 8, 1]; function filterRangeInPlace(arr, a, b) { return arr.filter(each=>{ return each > a && each < b }) }; arr = filterRangeInPlace(arr, 1, 4); console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM