最近开始学习前端,学习过程中学到了几个数组的迭代方法,觉得不仅很实用,还提高了代码可读性。分别是forEach()、map()、filter()、some()、every()。
在此之前,对数组操作我都是使用for循环来完成的,下面来个小栗子
//找出数组中大于18的数
const ages = [32, 15, 19, 12];
const nums = [];
for(let i = 0; i<ages.length;i++){
if(ages[i] >= 18){
nums.push(ages[i]);
}
}
console.log(nums);
forEach
那么,如何简化呢?用forEach()试试:
const ages = [32, 15, 19, 12];
const nums = [];
ages.forEach(function(value) {
if(value >= 18){
nums.push(value);
}
})
同样,也能得到相同的结果
- forEach定义:用于调用数组的每个元素,并将元素传递给回调函数
- forEach语法:array.forEach(function(currentValue, index, arr), thisValue) 以上三个参数中,只有第一个参数是必需的,其余两个参数可选。那么这三个参数分别是什么呢?上栗子:
ages.forEach(function(currentValue, index, arr) {
console.log(currentValue, index, arr)
})
filter
还能简化吗?可以!filter来实现!
const ages = [32, 15, 19, 12];
const adultPresent = ages.filter(function(age) {
return age >= 18;
})
- filter定义:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。顾名思义,filter就是一个过滤器,他将不符合条件的值过滤掉,留下符合条件的元素。
- filter语法:array.filter(function(currentValue,index,arr), thisValue),以上三个参数的说明与forEach一致。
map
先上栗子
const arr = [1, 2, 3, 4];
// 原数组的平方
const SquareArr= arr.map(function(item) {
return item * item;
})
console.log(SquareArr)
- map定义:返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。它体现的是一个映射关系.
- map语法:array.map(function(currentValue,index,arr), thisValue),以上三个参数的说明也与forEach一致。
some
const ages = [32, 15, 19, 12];
const adultPresent = ages.some(function(age) {
return age >= 18;
})
- some定义:用于检测数组中的元素是否满足指定条件(函数提供)
- some语法:array.some(function(currentValue,index,arr),thisValue),参数说明与以上方法一致。
- 注:当some找到符合条件的值,则直接return true,不再继续迭代。
every
const ages = [32, 15, 19, 12];
const adultPresent = ages.every(function(age) {
return age >= 18;
})
- every定义:方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。
- every语法:array.every(function(currentValue,index,arr),thisValue),参数说明与以上方法一致。
- 注:every一旦迭代到不符合条件的值,直接return false,不再继续迭代。
注:以上五个迭代方法都不会对空数组进行操作。
初学前端,欢迎指点。