以下代码的输出是NaN,为什么?

时间:2019-08-06 09:22:16

标签: javascript javascript-objects reduce

在这里,我正在尝试添加“ order_total”属性。我使用过reduce方法,如果仅尝试使用数组,则相同的代码可以正常工作,但是当我在对象数组上实现时,会得到NaN。

var user = {
    id: 16,
    username: 'smith',
    email: 'smith@gmail.com',
    order: [
        {
            id: 71,
            order_number: 'DCT-123',
            order_total: 12000,
        },
        {
            id: 71,
            order_number: 'DCT-345',
            order_total: 7000,
        },
        {
            id: 71,
            order_number: 'DCT-321',
            order_total: 2000,
        }
    ]
};

var result = user.order.reduce(function(a, b) {
    return a.order_total + b.order_total;
}); 

console.log(result); 

2 个答案:

答案 0 :(得分:2)

reduce回调中的参数a是累加器,而不是对象的属性。请参阅here,以了解有关reduce的更多信息

var user = {
    id: 16,
    username: 'smith',
    email: 'smith@gmail.com',
    order: [
        {
            id: 71,
            order_number: 'DCT-123',
            order_total: 12000,
        },
        {
            id: 71,
            order_number: 'DCT-345',
            order_total: 7000,
        },
        {
            id: 71,
            order_number: 'DCT-321',
            order_total: 2000,
        }
    ]
};

var result = user.order.reduce(function(a, b) {
    return a+b.order_total;
},0); 

console.log(result); 

答案 1 :(得分:1)

您返回数字,而不是对象。

var result = user.order.reduce(function(a, b) {
    //                                  ^        object
    //                                     ^     object
    return a.order_total + b.order_total;  //    number
}); 

您需要一个起始值为零并添加该属性的值。

var user = {
    id: 16,
    username: 'smith',
    email: 'smith@gmail.com',
    order: [
        {
            id: 71,
            order_number: 'DCT-123',
            order_total: 12000,
        },
        {
            id: 71,
            order_number: 'DCT-345',
            order_total: 7000,
        },
        {
            id: 71,
            order_number: 'DCT-321',
            order_total: 2000,
        }
    ]
};

var result = user.order.reduce(function(total, a) {
    return total + a.order_total;
}, 0); 

console.log(result);