ES6新增数组方法

js中数组方法虽然很多很杂,看起来不好记,但是如果你用心总结一下的话还是比较好记的,而且熟记这些方法也一定会对你的工作起到非常积极的作用,下面我们来总结一下

1.forEach()

let arr = [1,2,3,'aaa','bbb'];
arr.forEach((item,index)=>{
    console.log(item,index)
})
//输出结果
//1 0
//2 1
//3 2
//'aaa' 3
//'bbb' 4
//forEach有两个参数,第一个是数组中的元素,第二个是下标

2.map()

let arr = [1,2,3,5,6];
let a = arr.map((item,index)=>{
	console.log(item,index)	
  	return item>2
})
console.log(a)

/*
> 1 0
> 2 1
> 3 2
> 5 3
> 6 4
> Array [false, false, true, true, true]最关键的是会返回一个数组
*/

3.filter()

let arr = [1, 2, 4, 5, 6, 9, 10, 15];
let r = arr.filter((item,index)=>{
  console.log(item,index)
    return item % 2 !== 0;
});
console.log(r)
/*
> 1 0
> 2 1
> 4 2
> 5 3
> 6 4
> 9 5
> 10 6
> 15 7
> Array [1, 5, 9, 15]
*/

4.reduce()这个方法也有两个参数,但是与其他方法都不一样,第一个参数是临时的值,第二个参数才是数组的值,如我们实现一个求和的方法

let arr = [1, 2, 4, 5,];
let r = arr.reduce((tem,item)=>{
  	console.log(tem,item)
    return tem+item
});
console.log(r)
/*
> 1 2
> 3 4
> 7 5
> 12

特别注意第一个参数是一个临时的值
*/

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值