• vue中三种for循环与高阶函数(filter、map、reduce)的使用


    for循环的三种用法

    1、第一种是我们平常用的最多的for循坏 如: 普通的for循环 ,显得繁琐,i为for为数组赋予的序号

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

    2、第二种for in 循坏,in对应的是数组对象名字,i 也是数组的序号

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

    3、第三种,item代表的是数组里具体的其中一个元素

    let totalPrice = 0
      for (let item of this.books) {
      totalPrice += item.price * item.count
    }

    显然第三种for 更直接有简便,下面用这第三种for循环来实现对数组进行判断,改变和汇总操作

    1、需求: 取出所有小于100的数字

    let newNums = []
      for (let n of nums) {
        if (n < 100) {
          newNums.push(n)
       }
    }

    2、需求:将所有小于100的数字进行转化: 全部*2

    let new2Nums = []
      for (let n of newNums) {
        new2Nums.push(n * 2)
    }
    console.log(new2Nums);

    3、需求:将所有new2Nums数字相加,得到最终的记过

    let total = 0
      for (let n of new2Nums) {
        total += n
    }
    console.log(total);

    上面的操作虽然实现了这三种需求,但是还是太繁琐,使用高阶函数(filter、map、reduce)可以更便捷的实现需求
    第一种是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  //这里返回了 10 20 40 50
     })
    console.log(newNums);

    第二种是map函数的使用:对数组进行遍历了一遍,并且return 回数组 参数也是回调函数

    // 20, 40, 80, 100
    let new2Nums = newNums.map(function (n) { // 20
      return n * 2
    })

    第三种是reduce函数的使用 ,参数有两个,还分别是回调函数 和 preValue 的初始值
    reduce作用对数组中所有的内容进行汇总

    let total = new2Nums.reduce(function (preValue, n) {
      return preValue + n   //这个preValue就代表上一个值,比如当 preValue 0 ,n 为20 时候 返回20
                            //后面当  preValue就等于 20 ,那么 n 自然就为40  结果是60
    }, 0)    
    console.log(total);
    //第一次: preValue 0 n 20
    //第二次: preValue 20 n 40
    //第二次: preValue 60 n 80
    //第二次: preValue 140 n 100
    //total:240
  • 相关阅读:
    redis命令
    eclipse error pages 打红X的解决方法
    探究adroid活动
    Javascript基本算法演练 Seek and Destroy
    c语言结构体排序示例
    android studio 环境配置
    git学习
    栈用于2进制转换10进制
    html和js
    js
  • 原文地址:https://www.cnblogs.com/windok/p/15659075.html
Copyright © 2020-2023  润新知