代码之家  ›  专栏  ›  技术社区  ›  user3552178

Reduce函数说:推送不是函数[重复]

  •  -1
  • user3552178  · 技术社区  · 5 年前

    代码如下

    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);
    

    但他说: 类型错误:accumlator.push不是函数 at reducer(/home/user/list1.js:2:56) 在Array.reduce()

    有什么建议吗?

    1 回复  |  直到 5 年前
        1
  •  4
  •   Jacob    5 年前

    push 不返回数组;相反,它回来了 undefined 因此对于第一次迭代, accumulator 将是空数组,但对于第二次迭代,它将是 未定义 .

    我推荐 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 }));