多种循环方式:
totalPrice(){
let totalPrice = 0
// 1.普通for循环
// for(let i=0; i < this.books.length; i++){
// totalPrice+=this.books[i].price * this.books[i].count
// }
// 2. i in books
// for(let i in this.books){
// totalPrice+= this.books[i].price * this.books[i].count
// }
// 3. item in books
for(let item of this.books){
totalPrice+=item.price*item.count
}
return totalPrice
}
编程范式:命令式编程/声明式编程
编程范式:面向对象编程(第一公民:对象)/函数式编程(第一公民:函数)
filter map reduce函数的使用
filter中的回调函数有一个要求,必须返回一个布尔值。
true:函数内部自动将回调的n加入新数组,false过滤掉
const nums = [11,333,444,4,55]
let newNum= nums.filter(function (n) {
return n<100
})
console.log(newNum)
// 2. map
let new2Nums = newNum.map(function (n) {
return n * 2
})
console.log(new2Nums);
// 3. reduce 对数组中所有内容进行汇总
let total = new2Nums.reduce(function (preValue,n) {
return preValue + n
},0)
函数式编程
const nums = [10,333,444,20,40,50]
let total = nums.filter(function (n) {
return n < 100
}).map(function (n) {
return n *2
}).reduce(function (preValue,n) {
return preValue + n
})
console.log(total)
箭头函数:
const nums = [10,333,444,20,40,50]
let total = nums.filter(n => n < 100).map(n => n * 2).reduce((pre,n) => pre+n)
console.log(total)