function count(arr, item) {
    let sum = 0;
    arr.forEach(i => {
        if(i === item) sum++;
    });
    return sum;
}
function count(arr, item) {
    return arr.filter(i => i === item).length;
}

JavaScript 中的 filter 是一个用于数组的高阶函数,它可以通过一个指定的回调函数来过滤数组中的元素,并返回一个新的数组,新数组只包含满足回调函数要求的元素。

filter 方法的语法如下:

array.filter(callback(element[, index[, array]])[, thisArg])

其中,array 表示要进行过滤的数组;callback 是一个回调函数,用于测试每个元素是否符合条件。callback 函数接受三个参数:

  • element:当前正在被遍历的数组元素。
  • index(可选):当前正在被遍历的数组元素的下标。
  • array(可选):正在被遍历的原始数组。

thisArg(可选):在执行回调函数时,callback 函数内部 this 的值。

filter 方法返回一个新数组,其中只包含符合条件的元素。

以下是一个简单的示例,演示如何使用 filter 方法来过滤出数组中的偶数:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});

console.log(evenNumbers); // [2, 4, 6, 8, 10]

在这个例子中,我们通过回调函数检查每个元素是否是偶数,最后返回一个只包含偶数的新数组。