Vue之js高阶函数07

js高阶函数之filter、map、reduce

1. filter

filter中的回调函数需要返回一个boolean值。若返回true,则本次回调的元素,加入到新数组中;若返回false,则过滤掉本次回调的元素,不会加入到新数组中。

数组2 = this.数组1.filter(function (i) {
          return true/false;
        })

在这里插入图片描述

2. map

map:对数组中的所有元素都进行操作时使用。

数组2 = this.数组1.map(function (i) {
          return xxx;
        })

在这里插入图片描述

3. reduce

reduce:对数组中所有元素进行汇总。

//i为数组1中的元素(从第一个元素开始遍历),pre为i的前一个元素(默认第一次pre为0)
数组2 = this.数组1.reduce(function (pre, i) {
          return xxx;
        },y)

在这里插入图片描述

filter+map+reduce
在这里插入图片描述
在这里插入图片描述
简化
在这里插入图片描述

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3js高阶函数</title>
</head>
<body>
  <div id="info">
    <h3>数组num={{num}}</h3>
    <h3>
      filter高阶函数:去除num中小于100的数存到newNum1中
      <button @click="getNewNum1">getNewNum1</button>
    </h3>
    <h3>newNum1 = {{newNum1}}</h3>

    <h3>
      map高阶函数:将newNum1的元素乘以2之后存到newNum2中
      <button @click="getNewNum2">getNewNum2</button>
    </h3>
    <h3>newNum2 = {{newNum2}}</h3>

    <h3>redece高阶函数:计算newNum2的总和</h3>
    <h3>newNum2Total = {{newNum2Total}}</h3>
    <h3>简化得:最总结果为:{{getLastNum}}</h3>
  </div>

  <script src="../../js/vue.js"></script>
  <script>
    const info = new Vue({
      el : "#info",
      data : {
        num: [444, 21, 54, 301, 14, 440, 97, 169, 42, 98],
        newNum1: [],
        newNum2: [],
      },
      methods : {
        getNewNum1(){
          this.newNum1 = this.num.filter(function (i) {
            return i < 100;
          })
        },
        getNewNum2(){
          this.newNum2 = this.newNum1.map(function (i) {
            return i * 2;
          })
        },
      },
      computed: {
        newNum2Total(){
          return this.newNum2.reduce(function (pre, i) {
            console.log(pre)
            return pre + i;
          },0)
        },
        
        getLastNum(){
          return this.num.filter(function (i){
            return i < 100;
          }).map(function (i) {
            return i * 2;
          }).reduce(function (pre, i) {
            return pre + i;
          },0)
        }
      }

    })
  </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值