一行多语句的箭头函数

Arrow function with multiple statements in one line

最近我发现一个简单的箭头函数,例如这张地图中的回调

[1, 2, 3, 4, 5, 6].map(item => {
    console.log(item) // or anything else
    return item - 1;
})

我可以像这样重写一行命令

[1, 2, 3, 4, 5, 6].map(item => (console.log(item), item - 1))

我可以使用由 , 划分的尽可能多的语句,最后一个参数将始终是 return 值。它对我来说看起来很酷,但在箭头函数文档中找不到关于此语法的任何信息。任何人都可以解释这种语法或只是指向我找到文档的地方吗?

您正在使用逗号运算符计算多个表达式: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

本质上,它允许您在一条语句中执行多项操作。它通常用于 for 循环并在单个语句中分配多个变量,例如:var a = 1, b = 2;.

仅仅因为它有效,并不意味着它是个好主意。它会降低您的代码的可读性和调试难度。

请参阅 the Comma Operator 上的 MDN 文档。

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.