Vue中,filter、map、reduce的用法

一、filter遍历数组:查询数组,查询数组的指定的值(>,<,=)

const arr = [10,20,111,222,444,40,50]

1.使用for循环:

let newArr = []
for(let n of arr){
	if(n < 100){
	newArr.push(n)
	}
}
console.log(newArr);//[10,20,40,50]

2.使用filter循环:

let newArr = arrs.filter(function(n){
	return n < 100
})
console.log(newArr);//[10,20,40,50]

 二、map遍历数组,并返回一个值(用于计算)

数组 let newArr=[10,20,40,50],把数组中的每个元素*2,再添加到新的数组中

map函数会将回调函数返回的值作为新值传入到新数组中

1.使用for循环:

let new2Arr = []
for (let n of newArr){
	new2Arr.push(n * 2)
}
console.log(new2Arr);//[20,40,80,100]

2.使用map循环:

let new2Arr = newArr.map(function(n){
	return n*2
})
console.log(new2Arr);//[20,40,80,100]

三、reduce循环数组:求和(每个元素单独操作/判断,并返回结果);

数组 let new2Arr=[20,40,80,100]

1.使用for循环:

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

2.使用reduce:

语法:reduce(function(preValue,n),initiaValue)

使用reduce必须要传入这几个参数,一个回调函数和一个初始化值initiaValue。reduce也会遍历数组,当没有传入初始值时,第一个preValue是数组中第一个元素,n数组是第二个元素。但是当传入初始值(initiaValue)后,第一个preValue将是initivalValue,n将是数组中的第一个元素。从第二次开始,后面的preValue取决于回调函数中返回的值。

执行步骤如下:

new2Arr.reduce(function(preValue,n){
console.log('preValue=',preValue,'n=',n);
	return 100
},0)

//第一次 preValue=0 n=20
//第二次 preValue=100 n=40
//第三次 preValue=100 n=80
//第四次 preValue=100 n=100
let total = new2Arr.reduce(function(preValue,n){
	return preValue + n
},0)
console.log(total);//240

//第一次 preValue=0 n=20
//第二次 preValue=20 n=40
//第三次 preValue=60 n=80
//第四次 preValue=140 n=100
//return 240

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值