JavaScript:filter()方法返回原始数组而不进行过滤

时间:2019-05-29 21:02:15

标签: javascript arrays function methods filter

我下面使用filter()数组函数编写以下代码。

arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

console.log(test(arr))

我的代码返回了原始数组([12,5,8,130,44]),并且根本没有进行过滤。我究竟做错了什么?

注意:我想为此使用filter()方法。

2 个答案:

答案 0 :(得分:0)

您的代码缺少一些内容,但是您的方向正确。 Array.filter不会更改原始数组。设置变量 var filter ,并将其设置为等于功能测试。然后console.log(filter(arr))

答案 1 :(得分:0)

过滤器会返回一个新数组,因此根据您使用函数的方式,您很有可能正在查看原始数组,而您不能这样做,则需要查看过滤后的结果。

let arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

// The filtered results
console.log('The filtered array', test(arr))

// The original array
console.log('The original array', arr)

要在适当位置修改数组,可以使用while循环,然后拼接类似这样的元素,以在适当位置修改数组。

let arr = [12, 5, 8, 130, 44]

// Get the initial length of the array
let i = arr.length

// Loop backwards over the array as not to skip values when they get removed
while(--i) {
  if(arr[i] > 10) continue
  arr.splice(i, 1)
}

console.log(arr)

您也可以暂时将值分配回原始数组,而覆盖原始值。

let arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

// Assign the result back to arr
arr = test(arr)

// The new value of arr
console.log(arr)