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

Why can't I remove elements from the array?

这个函数应该删除小于 1 和大于 4 的元素,但它没有。数组还是一样。

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);

怎么了?

什么时候单个项目既小于 1 又大于 4?如果你想删除少于 1 多于 4 的项目,你需要做:

if (a > item || b < item)

您在调用函数时反转了参数。 你应该做

filterRangeInPlace(arr, 4, 1)

你基本上是将物品保持在给定范围内,而不是移除物品去保持物品这将 return 相同 也使用 filter 函数,它基本上遍历数组,就像 foreach 里面有两个参数 item 和 index 唯一的区别是过滤器在你 return true 时保持值,如果你 return假

您可以在此处查看有关过滤器的更多信息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);