【问题标题】:Understanding the find() method [duplicate]了解 find() 方法 [重复]
【发布时间】:2020-12-18 03:49:54
【问题描述】:

如果我这样写,我想知道为什么 arry.find() 会起作用:

const tour = tours.find(el => el.id === id);

但如果我这样写箭头函数:

const tour = tours.find((el) => {el.id === id});

有人能解释一下吗?在这两种情况下,我都会给出一个函数作为参数。

【问题讨论】:

  • 因为你使用{}的时候没有返回。

标签: javascript


【解决方案1】:

因为,您需要在回调函数中返回truefalse。所以这就是你的代码应该如何运行(在第二种情况下,当你使用代码块时):

const tour = tours.find((el) => {return el.id === id});

但是,箭头函数有一个速记,如果是单行语句,则不需要使用代码块,并且它自动返回语句的结果,所以你不需要需要显式使用return来返回条件语句的结果。

【讨论】:

    【解决方案2】:

    第一个是短线:

    const tour = tours.find(el => { return el.id === id });
    

    您需要在第二种情况下添加return,否则您会返回 undefined 并且过滤器仅适用于真实的返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2015-12-14
      • 1970-01-01
      相关资源
      最近更新 更多