作者 | 王涵0921链接 | https://www.jianshu.com/p/3bad039daebd
还记得我们用到死的for循环吗 ?有时候for循环是真的很耗性能不说 , 而且要写一堆代码 , 代码冗余 ..这里推荐大家几个特别好用的数组的方法 , 再不用for循环 , 一句话搞定!~~
1、filter()
创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。注意⚠️ :1、filter() 不会对空数组进行检测。2、filter() 不会改变原始数组。
array.filter(function(currentValue,index,arr), thisValue)
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)
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)
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)
const arr = [1, 2, 3, 4]
arr.forEach(val =>{
console.log(val)
}) // 1 2 3 4