📜  JavaScript 中对象数组的总和 - 无论代码示例

📅  最后修改于: 2022-03-11 14:58:31.736000             🧑  作者: Mango

代码示例1
class fruitCollection extends Array {
    sum(key) {
        return this.reduce((a, b) => a + (b[key] || 0), 0);
    }
}
const fruit = new fruitCollection(...[
    {  description: 'orange', Amount: 50},
    {  description: 'orange', Amount: 50},
    {  description: 'apple', Amount: 75},
    {  description: 'kiwi', Amount: 35},
    {  description: 'watermelon', Amount: 25 },]);

console.log(fruit.sum('Amount'));