减少功能说:推不是功能

时间:2020-11-06 22:27:13

标签: javascript node.js

代码是这样的

const reducer = (accumlator, currentVal) => accumlator.push( {id: currentVal} );

const ids = ['123', '456'];

// want to get [{id:123}, {id:456}]
const rs = ids.reduce(reducer, []);

console.log(rs);

但是说: TypeError:accumlator.push不是函数 在减速器上(/home/user/list1.js:2:56) 在Array.reduce()

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

push不返回数组;而是返回undefined。因此,对于第一次迭代,accumulator将为空数组,而对于第二次迭代,它将为undefined

我建议改用concat

const ids = ['123', '456'];

// want to get [{id:123}, {id:456}]
const rs = ids.reduce((accumlator, currentVal) => accumlator.concat([{id: currentVal}]), []);

...或使用map进行更简单的实现:

const rs = ids.map(id => ({ id }));