() => {…}和() =>有什么不同?
+----+--------------------------------+---------------------------------------+
| # | 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
() => {
return {key: value}
}
() => {key: value}
() => ({key: value})
示例:4
() => {
const a = 1
const b = 2
return a * b
}
() => 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 引擎自动完成的操作。显式则需要我们手动实现。我们可以以任何术语类比理解。