JS高阶函数使用

69 阅读1分钟

首先是for循环的一种简化写法,主要针对数组遍历

 1.常规for循环
             let price=0;
             for(let i = 0;i<this.books.length;i++){
                 price+=this.books[i].price*this.books[i].count;
             }
             return price;
             2.for(let i in this.books)
             let price=0;
             for(let i in this.books){
                 price+=this.books[i].price*this.books[i].count;
             }return price;
            3.for(let i of this.books)
            let price=0;
            for(let book of this.books){
                price+=book.price*book.count;
            }return price;

filter函数(过滤函数):中有一个回调函数,每读入数组中的一个元素便调用一次(返回一个Boolean值),当返回值为true时,函数内部将会自动将这次的回调的n加入新的数组,若为false,则过滤掉这次的n

const nums=[1,2,4,5,10,32,44];
let  newNums = nums.filter(function(n){
      return n<6;
})
console.log(newNums)
​
简洁写法:
let newNums = nums.filter(n => n<6);
//最后获得结果[1,2,4,5]

map函数(遍历函数):中有一个回调函数, 每读入数组中的一个元素便调用一次 ,并将返回值自动加入新的数组

const nums=[1,2,4,5,10,32,44];
let  newNums = nums.map(function(n){
      return n*2;
})
console.log(newNums)
​
简洁写法:
let newNums=nums.map(n => n*2)
//最后获得结果[2,4,8,10,20,64,88]

reduce函数(汇总函数):中有两个传入参数----reduce(参数一,参数二)

const nums=[1,2,4,5];
let  newNum = nums.reduce(function(preValue,n){
      return preValue+n;
},0)
console.log(newNum)
第一次:preValue 0 n 1
第二次:preValue 1 n 2
第三次:preValue 3 n 4
第四次:preValue 7 n 5
第五次:preValue 12
最后输出12
​
​
简洁写法:
let newNum = nums.reduce((preValue,n) => preValue+n)