首页 > 解决方案 > reduce 不是 Object.sum 的函数

问题描述

我有这个代码示例

let numbers = [1, 2, 3]
let summableNum = Object.assign({}, numbers, {
  sum: function() {
    return this.reduce(function(a, b) {
      return a + b
    })
  }
})

结果是:

{
  "0": 1,
  "1": 2,
  "2": 3,
  sum: f
}

summableNum[0]  // 1

当我执行 summableNum.sum() 时,我有这个错误

未捕获的类型错误:this.reduce 不是 Object.sum (:4:17) 处的函数:11:17

预期结果:

summableNum.sum() // 6

你能帮助我吗

标签: javascript

解决方案


summableNum{}对象,它没有.reduce属性。改用数组:

const numbers = [1, 2, 3];
const summableNum = Object.assign([], numbers, {
  sum() {
    return this.reduce((a, b) => a + b, 0);
  }
});

或者使用数组的副本:

const numbers = [1, 2, 3];
const summableNum = Object.assign(Array.from(numbers), {
  sum() {
    return this.reduce((a, b) => a + b, 0);
  }
});

推荐阅读