javascript - 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
你能帮助我吗
解决方案
你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);
}
});
推荐阅读
- java - 谷歌当前位置图
- java - 类级别的 Bean 验证不适用于泛型类
- git - VSTS API 提交差异
- python - Django CMS FieldError:类“PageUser”中的本地字段“created_by”与基类“User”中类似名称的字段冲突
- javascript - 使用 .insertBefore 放置 div 后使其可点击
- swift - TableViewController 中的多个自定义单元格
- python - (I)python 中 Luhn 算法的意外性能
- r - ggplot geom_tile,删除垂直白线
- pip - GDAL Virtualenv Python 3.6 安装
- kubernetes - 没有linux可以使用kubernetes吗?