程序员社区

JavaScript高阶函数的使用

测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title</title>
</head>
<body>
<div id="app">
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el:'#app',
    data:{
    }
  })
  //1.filter函数的使用
  const nums = [10,20,222,111,333,60];
  let newNums = nums.filter(function (n) {
    return n<100        //筛选小于100的数
  })
  console.log(newNums);
  //2.map函数的使用
  let newNums2 = newNums.map(function (n) {
    return n*2          //对筛选完的数乘2
   })
  console.log(newNums2);
  //3.reduce函数的使用
  //作用:对数组元素进行汇总
  let total = newNums2.reduce(function (preValue,n) {
    return preValue+n   //汇总
  },0)
  console.log(total);
  //三个函数合起来写,体现了函数编程思想
  let total2 = nums.filter(function (n) {
    return n<100
  }).map(function (n) {
    return n*2
  }).reduce(function (preValue,n) {
    return preValue+n
  },0)
  console.log(total2)
  //使用箭头函数,更简洁
  let total3 = nums.filter(n => n<100).map(n => n*2).reduce((preValue,n) => preValue+n)
  console.log(total3)
</script>
</body>
</html>

小结

1.filter
函数里面要传一个回调函数,函数必须返回一个boolean值
当返回true时,函数内部会自动将这次回调的n加入到新数组中,返回false的时候,就会过滤掉这次的n
2.map
如果你想对数组里的所有元素进行一个变换,就可以用这个函数,也是传一个回调函数作为参数
3.reduce
可以对数组的所有元素做一个汇总
reduce(参数1,参数2)
reduce(function (preValue,n) {
return preValue+n
},0)
参数1是一个回调函数,preValue是回调函数上一次的返回值,参数2是preValue的初始值

回顾购物车案例
当中的这一段

totalPrice(){
  let totalPrice=0;
  for(let i in this.books){
    totalPrice += this.books[i].price*this.books[i].count;
  }
  return totalPrice;
}   

可以用reduce方法简化成如下:

totalPrice(){
  return this.books.reduce(function (preValue,book) {
    return preValue + book.price * book.count
  },0)
}

赞(0) 打赏
未经允许不得转载:IDEA激活码 » JavaScript高阶函数的使用

一个分享Java & Python知识的社区