1. forEach
forEach函数接受的参数是个函数,函数里面有几个参数,第一个必选,是每一项的值。二三是可选,分别为下标和当前遍历的数组。可以循环类数组
let arr = ["hello", "world", "!!!"];
arr.forEach(function (item, index, arr) {
console.log(item + "---" + index + "---" + arr);
});
/*
* 输出:
* hello---0---hello,world,!!!
* world---1---hello,world,!!!
* !!!---2---hello,world,!!!
*/
注意: (1) forEach() 需要用 return 跳过循环中的一个迭代,跳过之后会执行下一个迭代。(2)没有办法终止或跳出forEach循环,除非抛出一个异常。
arr.forEach(function (item, index, arr) {
if (index === 1) return;
console.log(item + "---" + index + "---" + arr);
});
/*
* 此时会循环跳过index等于1的时候,但不会结束循环
* 输出:
* hello---0---hello,world,!!!
* !!!---2---hello,world,!!!
*/
2. map
map函数接受的参数是个函数。map即是 “映射”的意思 ,原数组被“映射”成对应新数组,不会影响原数组。只可以循环数组,不能循环类数组
arr.map(function (value, index) {
console.log(value + "---" + index);
});
/*
* hello---0
* world---1
* !!!---2
*/
let newArr = arr.map((value) => {
return value + "hhh";
});
console.log(newArr);
// [ 'hellohhh', 'worldhhh', '!!!hhh' ]
注意:forEach()和map()区别:
1、forEach:用来遍历数组中的每一项,这个方法执行没有返回值,不影响原数组
2、map:支持return(但return并不是结束循环哦),相当与原数组克隆了一份,把克隆的每项改变了,也不影响原数组
3. for…in
for…in 是es5标准, 此方法遍历数组效率低,主要是用来循环遍历对象的属性。
可以循环类数组
let obj = {
name: "xz",
age: 28,
height: "183cm",
};
for (item in obj) {
console.log(item + "---" + obj[item]);
// 注意:这里不能写onj.item,要写成obj[item]
}
/*
* name---xz
* age---28
* height---183cm
*/
4. for…of
for…of 一般用于数组 参考es6的for…of循环
可以循环类数组
let arr1 = ["a", "b", "c", "d"];
for (let a in arr1) {
console.log(a); // 0 1 2 3
}
for (let a of arr1) {
console.log(a); // a b c d
}
// 注意: for in 输出的是下标,而 for of 输出的是值
5. reduce
不会影响原数组
arr.reduce(function(prev,cur,index,arr){
...
}, init);
arr 表示原数组; prev 表示上一次调用回调时的返回值,或者初始值 init;cur 表示当前正在处理的数组元素;index 表示当前正在处理的数组元素的索引,若提供 init 值,则索引为0,否则索引为1;init 表示初始值
// 数组求和
let arr = [3, 9, 4, 3, 6, 0, 9];
arr.reduce(function (pre, cur) {
return pre + cur;
}, 0);
// 设置初始值0,所以开始时pre的值为0,cur的值为数组第一项3,相加之后返回值为3作为下一轮回调的prev值,然后再继续与下一个数组项相加,以此类推,直至完成所有数组项的和并返回。
// 数组去重
let newArr = arr2.reduce(function (prev, cur) {
prev.indexOf(cur) === -1 && prev.push(cur);
return prev;
},[]); //初始化prev为[]空数组
console.log(newArr); //[3, 9, 4, 6, 0];
/*
* 实现的基本原理如下:
* 初始化一个空数组
* 将需要去重处理的数组中的第1项在初始化数组中查找,如果找不到(空数组中肯定找不到),就将该项添加到初始化数组中
* 将需要去重处理的数组中的第2项在初始化数组中查找,如果找不到,就将该项继续添加到初始化数组中
* ……
* 将需要去重处理的数组中的第n项在初始化数组中查找,如果找不到,就将该项继续添加到初始化数组中
* 将这个初始化数组返回
*/
6. find
find()方法接受参数是个函数,返回数组中符合测试函数条件的第一个元素,否则返回undefined ,不会影响原数组
let newArr = [{name:"Jim",age:"20"},{name:"Lily",age:"18"},{name:"Mei",age:"18"},]
let obj = newArr.find((item)=>{
return item.age == '18'
})
console.log(obj); // { name: 'Lily', age: '18' }
7. filter
filter()方法接收三个参数:数组项的值、该项在数组中的位置(可选参数)和数组对象本身(可选参数)。这个方法对查询符合某些条件的所有数组项非常有用,不影响原数组
var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item, index, array){
return (item > 2);
});
alert(filterResult); //[3,4,5,4,3]
// 或者写成
filterResult = numbers.filter(item => item > 2);