数组中包含对象的三种求和方法

591 阅读1分钟

books:[

    {title:'vue基础教学',price:12.00},

    {title:'js基础教学',price:20.00},

    {title:'头脑风暴',price:14.00}

]

1.for循环

let total=0

for(var i=0;i<this.books.length;i++){

    total+=this.books[i].price

}

return total

2.for...in循环

let total=0

for(const i in this.books){

    total+=this.books[i].price

}

return total

3.for...of循环

let total=0

for(const i of this.books){

    total+=i.price

}

return total

4.reduce

return this.books.reduce((a,b)=>{

    return a+b.price

},0)