() => {...}与() =>的区别是什么?

13

我发现了一个奇怪的问题。

给定一个过滤器和一个对象数组,我想只选择与过滤器匹配的对象。

奇怪的是,这并不起作用。

this.state.articles.filter((article) => {
  article.category === filter 
})

虽然这样做

this.state.articles.filter((article) => article.category === filter )

我最初认为它们会有相同的评估结果,但事实并非如此。你有什么想法为什么会这样吗?


第一个使用了一块代码,因此需要一个返回语句。第二个使用箭头函数的隐式返回。 - ibrahim mahrir
3
"(article) => article.category === filter" 被翻译成了 "(article) => { return article.category === filter })"。 - epascarello
1
请参见 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions#The_arrow_function_expression_(%3E)。 - Gabriele Petrioli
1
这个怎么会有这么多赞?只是好奇——它在语言规范中,也在SO和其他地方有记录。 - Dave Newton
@DaveNewton 很难找到正确的信息,有时候仅仅通过对人们面临的某些问题进行交谈会更容易。我想人们喜欢交流,即使只是在像SO这样的静态论坛上。 - mark
如果 Stack Overflow 是一个咖啡馆或办公室的饮水机,那就太好了。但它不是,而且有明确的任务是减少重复问题、减少噪音并鼓励研究。 - Dave Newton
4个回答

27

当你在箭头函数中打开一个代码块 {} 时,return 不再是隐含的。

你必须把它写下来:

this.state.articles.filter((article) => {
  return article.category === filter 
})

9
“implicit return”是一个术语,如果有人想要在谷歌上搜索它。 - Max Baldwin
这相当于在ES5及更早版本中的 function(article){ [...] },而 (article) => article.category === filter 相当于 function(article){ return [...] } - Ismael Miguel
@IsmaelMiguel 不,它们不等同。 - dfsq
那么这些的等效物会是什么? - Ismael Miguel

8
JavaScript ES6箭头函数的工作方式可通过以下示例最好地描述:

let multiply1 = (number) => number * 2;
// When we are returning one value we can put this expression on the same line

// this is the same as:
let multiply2 = (number) => { return number * 2};

//when we have 1 argument we can omit the parentheses
let multiply3 = number => number * 2;


// When we want to write multiple line we have to put brackets like this:
let multiply4 = (number) => { 
console.log('inside arrow function');
return number * 2;
};

console.log(multiply1(2));
console.log(multiply2(2));
console.log(multiply3(2));
console.log(multiply4(2));

当箭头函数返回一个表达式时,不需要显式地写出 return 语句和方括号 {},这非常方便。这样可以使代码更加简洁。

5
() => {…}和() =>有什么不同?
+----+--------------------------------+---------------------------------------+
| #  | Using curly brace              | Without curly brace                   |
+-------------------------------------+---------------------------------------+
| 1. | Needs explicit return          | Returns the statement implicitly      |
| 2. | `undefined` if no return used  | Returns the value of expression       |
| 3. | return {} // ok                | {} // buggy, ({}) // ok               |
| 4. | Useful for multi-line code     | Useful for single line code           |
| 5. | Okay even for single line      | Buggy for multi line                  |
+----+--------------------------------+---------------------------------------+

以下是上述差异的示例:
示例1:
// Needs explicit return
() => {
  return value
}
// Returns the value
() => value

例子:2

// Returns undefined
() => {
  1 == true
}
// Returns true
() => 1 == true // returns true

例子:3

// ok, returns {key: value}
() => {
  return {key: value}
}
// Wrap with () to return an object
() => {key: value} // buggy
() => ({key: value}) // ok

示例:4
// Useful for multi-line code
() => {
  const a = 1
  const b = 2
  return a * b
}
// Useful for single line code
() => 1 * 2 

例子:5

// Okay even for single line code
() => { return 1 }
// Buggy for multi-line code
() => const a = 123; const b = 456; a + b; // buggy
() => 
     const a = 123
     const b = 456
     a + b // still buggy

使用filter函数时,需要使用return语句来通过测试:新数组中包含通过测试的元素。如果没有元素通过测试,则返回一个空数组。 因此,使用形式为() =>的函数时,隐式返回该值,它将通过测试,并正常工作。但是当你使用() => {...}时,你没有显式地返回该语句,因此不会按照你的期望工作。它只返回一个空对象。因此,为了使你的代码按照预期工作,你应该使用return语句:
this.state.articles.filter((article) => {
  return article.category === filter 
})

PS: 我在使用隐式和显式这两个词,那在 JavaScript 中它们具体是什么意思呢?

隐式指的是 JavaScript 引擎自动完成的操作。显式则需要我们手动实现。我们可以以任何术语类比理解。


2
区别在于,当您使用() => x时,它实际上意味着() => { return x },因此仅使用语句article.category === filter并没有任何作用,{ article.category === filter }没有明确返回任何内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接