javascript - 花括号会改变这个函数的读取吗
问题描述
我正在编写一个函数来使用 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 方法是否无法识别它。
解决方案
简短的回答:是的,它是不同的。你的 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]
推荐阅读
- python - 在 Python 中创建自动打字机机器人时出现问题
- google-chrome-extension - Web 扩展 manifest.json 文件中匹配模式的含义
- devops - 在 Papertrail 应用程序中搜索时如何使用正则表达式?
- javascript - webpack-dev-server npm run dev throwing TypeError: Cannot set property 'port' of undefined
- django - django:图像未加载
- angular - 离子角度的嵌套路由
- java - Springboot解密JNDI tomcat密码
- typescript - 错误访问类的受保护成员在控制台中显示没有错误
- java - 如何独立于客户端应用程序异步运行 oracle 存储过程?
- javascript - findTwins,它接受一个整数数组并找到两个相同的数字并返回重复两次的数字