JavaScript常用函数: Map、Filter、ForEach;
提示:以下是本篇文章正文内容,下面案例可供参考
1、Map
array.map(function(currentValue,index,arr), thisValue)
map() 不会改变原始数组
[55,44,66,11].map(function(currentValue,index,arr){
console.log(currentValue); //map() 方法按照原始数组元素顺序依次处理元素
console.log(index);
console.log(arr);
});
让数组通过某种计算得到一个新数组 (有返回值)
var newArr = [55,44,66,11].map(function(item,index,arr){
return item *10;
});
console.log(newArr);//[550, 440, 660, 110]
2、forEach
array.forEach(function(currentValue, index, arr), thisValue)
map() 与 forEach() 语法一致,能用
forEach()
做到的,map()
同样可以,但是存在区别。
区别:
- forEach()返回值是undefined,不可以链式调用;
- map()返回一个新数组,原数组不会改变.
3、filter
array.filter(function(currentValue,index,arr), thisValue)
filter是滤波的意思 从名字上看,就知道筛选过滤这样的活是filter来干的,返回一个新的对象数组,并不会改变原数组
var newArr = [32, 33, 12, 40].filter(function(item){
return item > 32;
});
console.log(newArr);//[33, 40]
结语
好的代码和粥一样,是用时间熬出来的