for,for in ,for of ,forEach,filter,map,reduce
一、js 遍历数组
-
普通 for 循环
var arr = [1,2,0,3,9]; for ( var i = 0; i <arr.length; i++){ console.log(arr[i]); } //1 2 0 3 9
-
forEach() :
ES5推出的,数组自带的循环,主要功能是遍历数组,实际性能比for还弱
arr.forEach(function(value,i){ console.log('forEach遍历:'+i+'--'+value); })
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210715192829569.png) > forEach这种方法也有一个小缺陷:你不能使用break语句中断循环,也不能使用return语句返回到外层函数。
-
map遍历:
map即是 “映射”的意思 用法与 forEach 相似,同样不能使用break语句中断循环,也不能使用return语句返回到外层函数。
arr.map(function(value,index){ console.log('map遍历:'+index+'--'+value); });
map遍历支持使用return语句,支持return返回值
var temp=arr.map(function(val,index){ console.log(val); return val*val }) console.log(temp);
> forEach、map都是ECMA5新增数组的方法,所以ie9以下的浏览器还不支持
-
for of 遍历(ES6 新增功能):
for-of循环不仅支持数组,还支持大多数类 数组对象(books[{},{},{},{}]),例如DOM NodeList对象。for-of循环也支持字符串遍历
for( let i of arr){ console.log(i); }// 1 2 0 3 9
二、js 遍历对象
- for-in遍历
- for-in 是为遍历对象而设计的,不适用于遍历数组。
- (遍历数组的缺点:数组的下标index值是数字,for-in遍历的index值"0",“1”,"2"等是字符串)
- for-in循环存在缺陷:循环会遍历对象自身的和继承的可枚举属性(不含Symbol属性)
const obj = {
a: 1,
b: 2,
c: 3,
d: 4
}
for (let i in obj) {
console.log(i);
// a b c d
// 取到的 i 是obj 对象的key
console.log(obj[i]);
// 取到的 obj[i] 是key 对应的 value
// 1 2 3 4
}
三、3 种高阶函数(filter,map,reduce)
1.filter(过滤)
-
filter函数中的回调函数有一个要求:必须返回一个boolean值
-
true 时,函数内部会自动将这次回调的 n 加入到新的数组中
-
false时,函数内部会自动过滤掉这次 n
const nums = [10,20,30,40,50,60,70] // 需求:取出所有大于30的数 let newNums = num.filter(function(n){ return n>20 }) console.log(newNums); ```
-
map(映射)函数的使用
const nums = [10,20,30,40,50,60,70] //需求:每个元素乘以2 再返回 let new2Nums = nums.map(function(n) { return 2*n }) console.log(new2Nums);
-
reduce 函数的作用:
对数组中所有的内容进行汇总 也就是计算数组总的值
- reduce 第一个参数时是一个回调函数(函数里面有四个参数 total 必填 为初始值或者是计算结束后的返回值,currentValue 必填 为当前元素)
- 第二个参数为传递给函数的初始值 可填可不填
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
const nums = [10,20,111,222,444,40,50] // 需求:取出比100小的数 再乘以2 再返回总的值 let total = nums.filter(n=> n<100).map(n=> n*2).reduce((pre,n) => pre + n); console.log(total);
注: 还是一句话 for in 遍历对象 { } for of 遍历数组 [ ]