【问题标题】:Push method not available in reduce' array accumulator?减少数组累加器中的推送方法不可用?
【发布时间】:2017-08-18 02:06:07
【问题描述】:

我有这个代码:

let fullConversations = conversationIdsByUser.reduce(async function(acc, conversation) {
                             const message = await MessageModel.find({ 'conversationId':conversation._id })
                                                               .sort('-createdAt')
                                                               .limit(1); // it returns an array containing the message object so I just get it by message[0]


                             return acc.push(message[0]);
                            },[]);

我的累加器是一个数组,message[0] 是我要推送的对象。但我有这个错误:

(node:516) UnhandledPromiseRejectionWarning: 未处理的承诺 拒绝(拒绝 id:2):TypeError:acc.push 不是函数

帮助?

【问题讨论】:

    标签: javascript mongoose


    【解决方案1】:

    这是因为Array.prototype.push() 返回数组的新长度,而不是数组本身。您的代码将运行 reducer 的一次迭代,将累积值设置为整数,然后在下一次迭代中失败。

    解决方法是修改后返回数组:

    let fullConversations = [{a: 1}, {b: 2}].reduce(function(acc, next) {
      console.log(acc.push(next))
      
      return acc
    }, []);
    
    console.log(fullConversations)

    但是请注意,您应该始终将纯函数传递给Array.prototype.reduce()。遵守这条规则本来可以让你从这个问题中解脱出来。示例:

    console.log([{a: 1}, {b: 2}].reduce((mem, next) => mem.concat([next]), []))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-05
      • 2015-06-04
      • 2022-01-15
      • 2018-01-23
      • 2022-01-08
      • 1970-01-01
      • 2020-04-06
      • 2018-07-29
      相关资源
      最近更新 更多