js中forEach、map、reduce、filter函数
原文:https://blog.csdn.net/liuxiao723846/article/details/106857447
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的新语法。
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
------------ 就像竹林的灯火,被风吹过,摇摇曳曳,但永不熄灭! ------------------------