vuejs中三种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
}
  1. 第二种for in 循坏,in对应的是数组对象名字,i 也是数组的序号
let totalPrice = 0
  for (let i in this.books) {
    const book = this.books[i]
    totalPrice += book.price * book.count
}
  1. 第三种,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)
}
}
  1. 需求:将所有小于100的数字进行转化: 全部*2
let new2Nums = []
  for (let n of newNums) {
    new2Nums.push(n * 2)
}
console.log(new2Nums);
  1. 需求:将所有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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Huang_xianlong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值