共计 671 个字符,预计需要花费 2 分钟才能阅读完成。
var books = [{name:’ 西游记 ’,author:’ 吴承恩 ’,price: 58,count:5},{name:’ 三国演义 ’,author:’ 罗贯中 ’,price: 68,count: 6},{name:’ 水浒传 ’,author:’ 施耐庵 ’,price: 48,count:8},{name:’ 红楼梦 ’,author:’ 曹雪芹 ’,price: 78,count:10}]
(1) 通过 for 循环 计算总价格
let totalPrice = 0
for(let i=0;i<this.books.length;i++) {this.totalPrice += this.books[i].price * this.books[i].count
}
(2)
let totalPrice = 0
for(let i in this.books) {this.totalPrice += this.books[i].price * this.books[i].count
}
(3)
let totalPrice = 0
for(let item of this.books) { // item 为每一项的下标
totalPrice += item.price * item.count
}
(4) forEach
let totalPrice = 0
this.books.forEach(item => {totalPrice += item.price * item.count})
(5) map 返回一个新数组
let totalPrice = 0
this.books.map(item => {return totalPrice += item.price * item.count})
正文完