reduce 计算错误

Wrong calculation with reduce

谁能解释为什么这等于 052 而不是 7?我就是不明白。

 products: [
            {id: 1, name: 'Baju', Hours: 2},
            {id: 2, name: 'Celena', Hours: 5}
            ],

 subTotalTest: function (){
            return this.products.reduce((total, item) => {
                return total + item.Hours
            },0)

当我调用 subTotalTest 时,我得到的是 052 而不是我期望和想要的 7。

您得到的产品数组 'Hours' 是字符串而不是整数,这就是为什么它被连接而不是相加的原因。

试试这个:

subTotalTest: function (){
        return this.products.reduce((total, item) => {
            return total + parseInt(item.Hours)
        },0)

在 parseInt 中包含基数参数是更好的做法

subTotalTest: function (){
        return this.products.reduce((total, item) => {
            return total + parseInt(item.Hours, 10)
        },0)