javaScript中操作数组的高阶方法filter、map、reduce及for循环三种遍历形式
我们在实际开发会遇到很多对数组的操作,现在我们学习几个高阶方法来更加优雅的操作数组。
下面的三个需求中,会演示for循环的三种遍历数组的方式,每个需求对应一种遍历方式。
filter方法过滤数组
需求:有一个数组,我们需要把数组中的值给给筛选一下。
一般操作
例子:找出数组中小于100的数,我们常规的写法,就如下代码:
// 注:下面的const、let都是ES6的新语法,不懂的可以当做var
// 创建一个数组
const nums = [12, 32, 31, 987, 323, 234, 343, 34, 23, 345]
// 需求一:过滤掉大于100的值
let new1nums = []; // 创建一个空数组保存数据
for (let i=0; i<nums.length; i++){ // for遍历
if(nums[i] <= 100){
new1nums.push(nums[i]); // 把数组nums中小于100的值添加到新数组
}
}
console.log("new1nums:" + new1nums);
filter方法
可以用filter方法更加优雅的满足这个需求:代码如下
const nums = [12, 32, 31, 987, 323, 234, 343, 34, 23, 345]
// 需求一:过滤掉大于100的值
let new1nums = nums.filter( function (n) {
return n < 100; // 如果n小于100,那就是true,就把当前n存入临时数组
// 上面写法看不懂可以看这个写法
// if (n < 100){
// return true;
// }
// return false;
})
console.log(new1nums);
方法解析:
nums.filter方法传入一个function方法,里面的值n就是数组nums里面的值的遍历,如上例子:
- 第一次:n = 12
- 第二次:n = 32
- 第三次:n = 31
…
方法的返回值是一个boolean值, - true:表示把当前n的值放到一个临时数组里面。
- false:表示不把当前n的值放到数组里面。
最后把这个临时数组当做方法的返回值,我们接收一下就好了。
map方法改变数组
需求:把数组中的所有数都乘以10
一般操作
const nums = [12, 32, 31, 987, 323, 234, 343, 34, 23, 345]
let new2nums = []; // 创建一个新数组保存数据
for (let i in new1nums){ // for遍历的第二种形式
new2nums[i] = unms[i] * 10;
}
console.log("new2nums:" + new2nums);
map方法用
用map方法优雅的实现这个需求,代码如下:
const nums = [12, 32, 31, 987, 323, 234, 343, 34, 23, 345]
// 需求二:把nums中的数 乘以10
let new2nums = nums.map(function (n) {
return n * 10; // 把数组中的每个元素都乘以10
})
console.log(new2nums);
方法解析:
同上,还是传入一个方法,其中的参数n也是数组中值的遍历,
把返回值放入一个临时数组中,把这个最终的数组当做整个方法的返回值。
reduce方法
需求:求出数组中所有元素的和
一般操作
const nums = [12, 32, 31, 987, 323, 234, 343, 34, 23, 345]
// 需求三:求出nums中的数的总和
let total = 0; // 保存数据
for (let num of nums){ // for遍历的第三种形式
total += num;
}
console.log("total:" + total);
reduce方法
用reduce方法实现这个需求,代码如下:
const nums = [12, 32, 31, 987, 323, 234, 343, 34, 23, 345]
// 需求三:求出nums中的数的总和
let total = nums.reduce( function (preValue, n) {
return preValue + n;
}, 0)
console.log(total);
方法解析
reduce()方法传入两个参数,
- 参数一:第一个参数是一个方法回调。
- 参数二:是preValue的起始值
在参数一的方法中,又传入两个参数
- 参数一:preValue:表示上一次的返回值,(最开始没有,所以要赋一个初始值,就是reduce()方法的第二个参数,例子中赋值为0)
- 参数二:数组的遍历。
此方法有点绕,详细说一下:
现在上面写的是:return preValue + n;就能完成整个数组相加的计算,
如果我们是写成: return 50;
那么他每次的方法传入值function(preValue, n)应该是
第一次:preValue=0; n=12;
第二次:preValue=50; n=32;
第三次:preValue=50; n=31;
第四次:preValue=50; n=987;
…
然后把最后的一个preValue当做返回值
方法中的preValue参数,就是此方法上一次return的值。初值自己设置。