1、forEach函数:
forEach是ES5扩展的语法,可以使用他遍历数组、对象,但是在forEach中不支持continue、break关键字,forEach中可以使用return来跳出当次循环,相当于continue。
1)forEach的语法:function(currentValue, index, arr),三个参数:
- currentValue:当前值;
- index:下标,从0开始;【可选】
- arr:整个数组;【可选】
2)forEach遍历数组:
var arr0 = [1,2,3];
arr0.forEach((v,i,arr)=> {
if (i === 2){
//break; 编译报错
//continue; 编译报错
return;
}
console.log(v);
});
输出:1 2
上面例子使用了箭头函数,是ES6的新语法。等价于下面:
arr0.forEach(function(v,i,arr){
if (i === 2){
return;
}
console.log(v);
});
3)遍历数组,并且修改其中元素:
var arr0 = [1,2,3];
arr0.forEach((v,i,arr) => {
arr[i] = v+100;
});
console.log("origin array:"+arr0);//101 102 103
注意:forEach不能直接遍历对象,在编译时会报错。
参考:https://www.runoob.com/jsref/jsref-foreach.html
2、map函数:
和forEach类似,map函数式ES6新语法。使用上和forEach一样。二者共同点:
- 函数都支持3个参数:v当前值,i当前索引,arr真个数组;
- 匿名函数中的this都是指Window;
- 只能遍历数组;
- 不支持break、continue;
不同点:
- forEach中return相当于continue,map中的return是将每次迭代遍历时处理后的元素添加到map返回值中;
- forEach没有返回值,map有返回值,返回值是一个新数组,新数组中的每个元素为每次map迭代时return的值。
var arr2 = [2,3,4];
var val = arr2.map((v,i,arr) => {
arr[i] = v+100;
return v+1;
});
console.log(val);
console.log(arr2);
//输出:
[ 3, 4, 5 ]
[ 102, 103, 104 ]
参考:https://www.runoob.com/jsref/jsref-map.html
https://juejin.im/post/5c999386e51d456d246deea1
3、filter函数:
和forEach、map类似,filter函数式ES6新语法。使用上和forEach、map一样。共同点:
- 函数都支持3个参数:v当前值,i当前索引,arr真个数组;
- 匿名函数中的this都是指Window;
- 只能遍历数组;
- 不支持break、continue;
不同点:
- forEach中return相当于continue,map中的return是将每次迭代遍历时处理后的元素添加到map返回值中,filter中的return是用来判断本次迭代是否将元素放到返回之中;
- forEach没有返回值,map有返回值,返回值是一个新数组,新数组中的每个元素为每次map迭代时return的值;filter也有返回值,返回值是一个新数组,新数组中的每个元素为每次filter迭代时return为true的值。
var arr3 = [5,6,7];
var val3 = arr3.filter((v,i,arr) => {
arr[i] = v+100;
if (v === 6) {
return false;
} else {
return true;
}
});
console.log(val3);
console.log(arr3);
//输出
[ 5, 7 ]
[ 105, 106, 107 ]
参考:https://juejin.im/post/5cdbb14ef265da036902bb22
https://www.runoob.com/jsref/jsref-filter.html
4、reduce函数:
和forEach、map类似,reduce函数式ES6新语法。使用上和forEach、map一样。共同点:
- 函数都支持4个参数:t初始值或者计算后的返回值【必填】,v当前值,i当前索引,arr真个数组;
- 匿名函数中的this都是指Window;
- 只能遍历数组;
- 不支持break、continue;
var arr4 = [6,7,8];
var val4 = arr4.reduce((t,v,i,arr) => {
console.log(v);
arr[i] = v+100;
return t*10;
});
console.log("----"+val4);
console.log(arr4);
//输出
7
8
----600
[ 6, 107, 108 ]
参考:https://m.runoob.com/jsref/jsref-reduce.html
https://juejin.im/post/5ec653ae51882543253366b2