1.for循环遍历简化
// 1.普通的for循环
// let totalPrice = 0
// for (let i = 0; i < this.books.length; i++) {
// totalPrice += this.books[i].price * this.books[i].count
// }
// return totalPrice
//这里i代表数组里的序号
// 2.for (let i in this.books)
// let totalPrice = 0
// for (let i in this.books) {
// const book = this.books[i]
// totalPrice += book.price * book.count
// }
//
// return totalPrice
//这里i代表数组的每一项
// 3.for (let i of this.books)
// let totalPrice = 0
// for (let item of this.books) {
// totalPrice += item.price * item.count
// }
// return totalPrice
2.高阶函数
高阶函数:英文叫Higher-order function。JavaScript的函数其实都指向某个变量。既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
编写高阶函数,就是让函数的参数能够接收别的函数。
filter函数的使用 ----过滤
// filter中的回调函数有一个要求: 必须返回一个boolean值
// true: 当返回true时, 函数内部会自动将这次回调的n加入到新的数组中
// false: 当返回false时, 函数内部会过滤掉这次的n
const nums = [10, 20, 111, 222, 444, 40, 50]
let newNums = nums.filter(function (n) {
return n < 100
})
console.log(newNums);
map函数的使用 ----映射
//map中的回调函数会对n进行处理,返回处理后的n加入到新数组中
let new2Nums = newNums.map(function (n) {
return n * 2
})
console.log(new2Nums);
reduce函数的使用 ----汇总
//reduce中的回调函数会对数组中所有的内容进行汇总
//reduce中的回调函数必须接收至少两个参数
//reduce会把结果继续和序列的下一个元素做累积计算
let total = new2Nums.reduce(function (preValue, n) {
return preValue + n
}, 0)
console.log(total);
// 第一次: preValue 0 ,n 20
// 第二次: preValue 20 ,n 40
// 第二次: preValue 60 ,n 80
// 第二次: preValue 140 ,n 100
// 最终结果: 240
函数可以一起使用
// 这里使用箭头函数进行简写
const nums = [10, 20, 111, 222, 444, 40, 50]
let total = nums.filter(n => n < 100).map(n => n * 2).reduce((pre, n) => pre + n);
console.log(total);