【问题标题】:Why doesn't JS complier recognize this call to Array.prototype.filter为什么 JS 编译器不能识别对 Array.prototype.filter 的调用
【发布时间】:2020-05-08 04:23:57
【问题描述】:

我试图弄清楚为什么我对 .prototype.filter 的调用给了我一个TypeError: curr.filter is not a function

const intersection = (arrays) => {
  return arrays.reduce((acc, curr) => {
    return curr.filter(el => acc.includes(el));
  });
};

console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));

据我了解,我声明了一个函数const intersection,它接收arrays,然后返回调用arrays.reduce 的结果,它“减少”过滤当前值并创建一个包含所有实例的新数组的结果累加器acc 包括当前值curr

由于过滤器在运行时创建了一个新数组,我认为这可以正常工作,但事实并非如此。我没看到什么?

【问题讨论】:

  • arrays 指的是您的第一个数组,它不是您传递给函数的所有数组的二维数组。您可以使用...arrays 获取传递给intersection 的所有参数的数组

标签: javascript arrays function functional-programming higher-order-functions


【解决方案1】:

使用数组rest parameter 将所有参数作为数组获取。在给定的代码中,您只采用第一个参数并忽略其余参数。

试试这个。

const intersection = (...arrays) => {
    console.log("arrays: ", arrays);
    return arrays.reduce((acc, curr) => {
      return curr.filter(el => acc.includes(el));
    });
  };
  console.log("Result:" , intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    相关资源
    最近更新 更多