Javascript减少速记不返回对象

me-*_*-me 1 javascript ecmascript-6

为什么一个工作而另一个不工作?

const b = {
  age: 20,
  name: "John Doe"
}

const sortedB = Object.entries(b).sort().reduce((acc, [key, val]) => acc[key] = val,{});
Run Code Online (Sandbox Code Playgroud)

输出:John Doe

最上面是省略了括号的括号,该括号表示自动返回acc。底部说的是大括号,这意味着您必须手动返回acc

  const sortedB = Object.entries(b).sort().reduce((acc, [key, val]) => {
    acc[key] = val;
    return acc;
  },{});
Run Code Online (Sandbox Code Playgroud)

输出:{年龄:20,姓名:“ John Doe”}

Fel*_*ing 5

最上面是省略了括号的括号,该括号表示自动返回acc

不,那不是什么意思。JavaScript如何/为什么应该知道返回acc

如果您具有仅将表达式作为主体的箭头功能,则将返回该表达式的结果。分配的结果就是分配的值。例:

var func = () => 1;
console.log(func()); // 1

func = x => x;
console.log(func(42)) // 42

func = (x, y) => y = 42;
console.log(func(1,2)); // 42

func = x => (x, 42);
console.log(func(21)); // 42

func = x => (42, x);
console.log(func(21)); // 21
Run Code Online (Sandbox Code Playgroud)

如果需要acc返回的值,则必须确保表达式的值等于该值,例如使用逗号运算符:

 (acc, [key, val]) => (acc[key] = val, acc)
 //                    ^^^^^^^^^^^^^^^^^^^
 //  the comma operator returns the result of the right expression
Run Code Online (Sandbox Code Playgroud)