首页 > 解决方案 > 花括号会改变这个函数的读取吗

问题描述

我正在编写一个函数来使用 concat 和 reduce 方法从 eloquent javascript 中展平一个数组。当我这样写我的代码时:

    function flatten(args){
       return args.reduce((current,i) =>{
           current.concat(i);
       },[] );
   }

   let arrays = [[1, 2, 3], [4, 5], [6]];
   console.log(flatten(arrays));

我收到以下错误:

current.concat(i);
                ^

TypeError: Cannot read property 'concat' of undefined

但是当我在本节中去掉大括号“{}”时:

前:

return args.reduce((current,i) =>{
        current.concat(i);
    },[] );

后:

return args.reduce((current,i) =>
        current.concat(i)
    ,[] );
}

它打印得很好。当找到一个初始化为 0 的总和时,这种格式可以正常工作。当 [] 在大括号“{}”内时,concat 方法是否无法识别它。

标签: javascriptarraysconcatreduce

解决方案


简短的回答:是的,它是不同的。你的 reducer 需要在函数中返回一个值。参数的值current等于调用最后一个reduce 函数调用的最后一个返回值。在第一次调用中,current参数等于reduce 函数调用(即[])的第二个参数中指定的初始值。

显式返回current带有大括号的版本也可以解决问题:

function flatten(args) {
   return args.reduce((current, i) => {
       return current.concat(i);
   }, []);
}

如果没有大括号,return 会隐式返回 concat 表达式返回的值,这是一个新数组。

有关箭头函数如何工作的更多信息,请查看MDN 的箭头函数文章。具体来说,本节讨论它是如何隐含的:

(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

以及本节:

// When the only statement in an arrow function is `return`, we can remove `return` and remove
// the surrounding curly brackets
elements.map(element => element.length); // [8, 6, 7, 9]

推荐阅读