一些好用的循环方式
1、for in
for(let i in array){}
这里 i是数组每一项的index
2、for of
for(let item of array){}
这里的item取到的是数组中每一项
3、js中的数组高阶函数
filter
arrayObject.filter(function(n){
//process
})
每从数组中取得一个元素,就会执行这个filter
的回调函数这个回调函数的要求的 返回值必须是 boolean,当返回为true时,函数内部会自动将这次回调的n加入到新的数组;当返回为false时,这个值则会被过滤掉
Map
arrayObject.map(function(n){
//process
})
每次从数组中取出一个函数,经过process部分处理后,return一个值,重新加入到数组当中
Reduce
对数组中所有项进行汇总
arrayObjact.reduce(function(previousValue,n){
},initialNum)
回调函数中的两个参数:
第一次,previousValue为0,之后的值为上一次调用函数return的值,n的值为每次从函数中取出来的项。
例如,有一个数组nums[10,20,30,40,50],运行
num.reduce((preVal,n)=>{
return 100
},0)
总共运行四次
第一次 | preVal=0 | n=10 |
---|---|---|
第二次 | preVal=100 | n=20 |
第三次 | preVal=100 | n=30 |
第四次 | preVal=100 | n=40 |
如果要求和:
num.reduce((preVal,n)=>{
return preVal+n
},0)
第一次 | preVal=0 | n=10 |
---|---|---|
第二次 | preVal=10 | n=20 |
第三次 | preVal=30 | n=30 |
第四次 | preVal=60 | n=40 |
最终,第四次回调函数中把preVal=60
和n=40
相加,得到数组的和100
reduce函数(手册描述):
from:https://www.runoob.com/jsref/jsref-reduce.html
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数 | 描述 |
---|---|
function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数:参数描述total必需。初始值, 或者计算结束后的返回值。currentValue必需。当前元素currentIndex可选。当前元素的索引arr可选。当前元素所属的数组对象。 |
initialValue | 可选。传递给函数的初始值 |
dex可选。当前元素的索引arr*可选。当前元素所属的数组对象。 |
| initialValue | 可选。传递给函数的初始值 |