【问题标题】:const is undefined within reduce methodconst 在 reduce 方法中未定义
【发布时间】:2017-04-30 12:13:58
【问题描述】:
avgPrice(data) {
    const min_price = data.min_price,
    max_price = data.max_price;

    console.log(min_price) //has value

    let x = _.reduce(data.custom_pricing, (a, b) => {
        a.min_price = Math.min(a.min_price, b.min_price);
        a.max_price = Math.max(a.max_price, b.max_price);
    }, { min_price:min_price, max_price:max_price });
}

我上面的代码有什么问题?我得到 min_price 是未定义的错误。但是当我执行 console.log 时,我的 const min_price 是有价值的。

【问题讨论】:

  • 不应该是let x = reducelet x = _.reduce
  • @Kinduser 这是_.reduce 不是Array.prototype.reduce
  • 究竟是什么错误?

标签: javascript ecmascript-6 lodash


【解决方案1】:

你必须从reduce返回(返回a,这样它才能用于下一次迭代)。

let x = _.reduce(data.custom_pricing, (a, b) => {
    a.min_price = Math.min(a.min_price, b.min_price);
    a.max_price = Math.max(a.max_price, b.max_price);

    return a; //<<<<<
}, { min_price:min_price, max_price:max_price });

无突变:

虽然我不明白为什么。

let x = _.reduce(data.custom_pricing, (a, b) => 
    ({ min_price: Math.min(a.min_price, b.min_price), max_price: Math.max(a.max_price, b.max_price) }), // create a new object and return it
    { min_price:min_price, max_price:max_price });

【讨论】:

  • 这改变了a,如何避免呢?
  • @GialaJefferson 检查编辑,尽管根本没有理由这样做。
  • 因为我在使用箭头函数时尽量避免返回使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2012-01-31
  • 2021-06-20
  • 2018-10-06
  • 1970-01-01
相关资源
最近更新 更多