问题描述
有人可以解释为什么它等于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。
解决方法
您获得的产品数组将“小时”作为字符串而不是整数,这就是为什么将其连接起来而不加起来的原因。
尝试一下:
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)