放弃for循环吧! 一句话搞定! 数组中好用的方法 :filter()、find()、map ()、forEach()...

640?wx_fmt=jpeg

作者 | 王涵0921链接 | https://www.jianshu.com/p/3bad039daebd

还记得我们用到死的for循环吗 ?有时候for循环是真的很耗性能不说 , 而且要写一堆代码 , 代码冗余 ..这里推荐大家几个特别好用的数组的方法 , 再不用for循环 , 一句话搞定!~~

1、filter()

创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。注意⚠️ :1、filter() 不会对空数组进行检测。2、filter() 不会改变原始数组。

array.filter(function(currentValue,index,arr), thisValue)

640?wx_fmt=other

const arr = [34, 65, 87, 48, 99];	
// filter() 方法	
const arrNew = arr.filter(num => {	
    return num >= 66;	
});	
console.log(arrNew); // [ 87, 99 ]

filter()会帮我们返回数组中所有符合条件的元素.此时不用在for循环了。

2、find()

方法返回通过测试(函数内判断)的数组的第一个元素的值。注意⚠️ :1、find() 对于空数组,函数是不会执行的。2、find() 并没有改变数组的原始值。执行过程如下 :1、数组中的每个元素都调用一次函数执行2、当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数3、如果没有符合条件的元素返回 undefined

array.find(function(currentValue, index, arr),thisValue)

640?wx_fmt=other

const arr = [34, 65, 87, 48, 99];	
// find() 方法	
const arrNew = arr.find(num => {	
    return num >= 66;	
});	
console.log(arrNew); // 87	

1、它们对于空数组都不会执行 , 会返回undefined

2、改变原数组

3、它们的区别就是 filter()方法 会返回所有符合条件的元素 , 并创建一个新数组 ,但是find()方法只会返回符合条件的一个元素

3、map()

返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。注意⚠️ :1.map() 不会对空数组进行检测。2.map() 不会改变原始数组。

array.map(function(currentValue,index,arr), thisValue)

640?wx_fmt=other

const arr = [1, 3, 4, 5];	
const res = arr.map((num)=>{	
    return num * num;	
})	
console.log(res) // [ 1, 9, 16, 25 ]

map()方法 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

4、forEach()

用于调用数组的每个元素,并将元素传递给回调函数。注意⚠️:forEach() 对于空数组是不会执行回调函数的。

array.forEach(function(currentValue, index, arr), thisValue)

640?wx_fmt=other

const arr = [1, 2, 3, 4]	
arr.forEach(val =>{	
    console.log(val)	
}) // 1  2  3  4	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值