gpt4 book ai didi

javascript - "TypeError: s.sum is not a function"尝试计算 javascript 对象的总属性值

转载 作者:行者123 更新时间:2023-12-03 01:22:34 24 4
gpt4 key购买 nike

我有一个 js 对象 JSON

var s = [  
{
"MONTH":" 2018-01",
"DEPARTMENT":"Legals",
"EMPLOYEE":"Smith A.",
"AMOUNT":"14289.66"
},
{
"MONTH":" 2018-01",
"DEPARTMENT":"Legals",
"EMPLOYEE":"Jonson B.",
"AMOUNT":"7408.05"
},
{
"MONTH":" 2018-01",
"DEPARTMENT":"Legals",
"EMPLOYEE":"Lee C.",
"AMOUNT":"10102.98"
}
]

我想计算 AMOUNT 属性的总和,并使用 next 来完成它(我使用了源 stackoverflow_count_summ 中的代码):

s.sum = function(items, prop){
return items.reduce( function(a, b){
return a + b[prop];
}, 0);
};

sTotal = s.sum(s, 'AMOUNT');

但我收到一条错误消息:“TypeError: s.sum 不是函数”

如何通过对象获取“AMOUNT”值的总和?

最佳答案

尝试使用此代码:

var s = [  
{
"MONTH":" 2018-01",
"DEPARTMENT":"Legals",
"EMPLOYEE":"Smith A.",
"AMOUNT":"14289.66"
},
{
"MONTH":" 2018-01",
"DEPARTMENT":"Legals",
"EMPLOYEE":"Jonson B.",
"AMOUNT":"7408.05"
},
{
"MONTH":" 2018-01",
"DEPARTMENT":"Legals",
"EMPLOYEE":"Lee C.",
"AMOUNT":"10102.98"
}
];
s.__proto__.sum = function(items, prop){
return items.reduce( function(a, b){
return a + +b[prop];
}, 0);
};

sTotal = s.sum(s, 'AMOUNT');
console.log(sTotal);

我将函数设置为 proto 并添加类型转换作为返回。我在 Firefox、Chrome 和 Edge 中测试了它,效果很好。

关于javascript - "TypeError: s.sum is not a function"尝试计算 javascript 对象的总属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com