如果未返回,reduce 函数的累加器未定义。为啥它会这样?
Posted
技术标签:
【中文标题】如果未返回,reduce 函数的累加器未定义。为啥它会这样?【英文标题】:Accumulator of reduce function undefined if not returned. Why does it behave like this?如果未返回,reduce 函数的累加器未定义。为什么它会这样? 【发布时间】:2021-11-01 20:50:44 【问题描述】:要减少的数组:
const users = [
firstname: "Sanket", lastname: "Shevkar", age: 22 ,
firstname: "Aniket", lastname: "Bhalla", age: 45 ,
firstname: "Tanvi", lastname: "Shinde", age: 21 ,
firstname: "Saif", lastname: "Siddiqi", age: 67 ,
];
const outout = users.reduce((acc, curr)=>
if(curr.age<45)
acc.push(curr.firstname);
, [])
抛出类型错误:
Uncaught TypeError: Cannot read property 'push' of undefined
我传递了一个空数组来初始化acc
(累加器),但它仍然抛出typeError。如果我最后return acc
,它就完美了。
const outout = users.reduce((acc, curr)=>
if(curr.age<45)
acc.push(curr.firstname);
return acc;
, [])
有人可以解释这种行为吗?
【问题讨论】:
“为什么会有这样的行为?” - 因为这就是规范所说的行为。 262.ecma-international.org/#sec-array.prototype.reduce(特别是步骤 9.c.ii) 当你可以在reduce
之前使用Array#filter
时,你为什么要使用reduce
进行过滤?
因为你需要在每次迭代中返回一些东西才能正常工作。你可以在这里阅读更多内容freecodecamp.org/news/reduce-f47a7da511a9
【参考方案1】:
Array.reduce 必须在每个循环中返回累加器
const users = [
firstname: "Sanket", lastname: "Shevkar", age: 22 ,
firstname: "Aniket", lastname: "Bhalla", age: 45 ,
firstname: "Tanvi", lastname: "Shinde", age: 21 ,
firstname: "Saif", lastname: "Siddiqi", age: 67 ,
];
const outout = users.reduce((acc, curr)=>
if(curr.age<45)
return acc.concat(curr.firstname);
return acc
, [])
console.log(outout)
【讨论】:
提问者已经知道这一点。它甚至在问题中。以上是关于如果未返回,reduce 函数的累加器未定义。为啥它会这样?的主要内容,如果未能解决你的问题,请参考以下文章
尽管向 createStore() 提供了 initialState,为啥我得到“Reducer [...] 在初始化期间返回未定义”?