我可以理解该ES6高阶功能的逻辑流程如何

发布于 2025-02-12 16:53:38 字数 503 浏览 0 评论 0原文

逻辑如何流向:(books)=> (架子)=> ...

const shelf1 = [
  { name: "name1", shelf: "a" },
  { name: "name2", shelf: "a" },
];
const shelf2 = [
  { name: "name3", shelf: "b" },
  { name: "name4", shelf: "b" },
];
const allBooks = [...shelf1, ...shelf2];

const filter = (books) => (shelf) => books.filter((b) => b.shelf === shelf);

const filterBy = filter(allBooks);
const booksOnShelf = filterBy("b");

我需要一个更详细的等同于这个缩短的表达,以帮助我消化这种魔术

how the logic flows at: (books) => (shelf) => ...

const shelf1 = [
  { name: "name1", shelf: "a" },
  { name: "name2", shelf: "a" },
];
const shelf2 = [
  { name: "name3", shelf: "b" },
  { name: "name4", shelf: "b" },
];
const allBooks = [...shelf1, ...shelf2];

const filter = (books) => (shelf) => books.filter((b) => b.shelf === shelf);

const filterBy = filter(allBooks);
const booksOnShelf = filterBy("b");

i need a more verbose equivalent to this shortened expression, to help me to digest that magic

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柏拉图鍀咏恒 2025-02-19 16:53:38

这是一个接受books参数并返回 new 函数的函数,该功能接受shelf参数。该功能分配给filterby,并调用的结果函数(数组)被分配给booksonshelf

内部功能将其引用books返回时,通常称为闭合

const shelf1=[{name:"name1",shelf:"a"},{name:"name2",shelf:"a"}],shelf2=[{name:"name3",shelf:"b"},{name:"name4",shelf:"b"}];

const allBooks = [...shelf1, ...shelf2];

function filter(books) {
  return function (shelf) {
    return books.filter(function (b) {
      return b.shelf === shelf;
    });
  };
}

// `filter` returns a new function which
// is assigned to `filterBy`. That function accepts
// a `shelf` argument
const filterBy = filter(allBooks);

// The result of calling that new function with
// argument 'b' is assigned to `booksOnShelf`
const booksOnShelf = filterBy('b');

console.log(booksOnShelf);

It's a function that accepts a books argument and returns a new function that accepts a shelf argument. That function is assigned to filterBy, and the result of calling that function (an array) is assigned to booksOnShelf.

The inner function maintains a reference to books when it's returned, and is generally called a closure.

const shelf1=[{name:"name1",shelf:"a"},{name:"name2",shelf:"a"}],shelf2=[{name:"name3",shelf:"b"},{name:"name4",shelf:"b"}];

const allBooks = [...shelf1, ...shelf2];

function filter(books) {
  return function (shelf) {
    return books.filter(function (b) {
      return b.shelf === shelf;
    });
  };
}

// `filter` returns a new function which
// is assigned to `filterBy`. That function accepts
// a `shelf` argument
const filterBy = filter(allBooks);

// The result of calling that new function with
// argument 'b' is assigned to `booksOnShelf`
const booksOnShelf = filterBy('b');

console.log(booksOnShelf);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文