Array.map方法
前言
上回我们介绍了forEach()方法,今天再来介绍一个遍历数组的方法——Array.map(),它的用法跟forEach方法类似。我们今天重点讲一下map和forEach的区别。
1.map()方法
语法:array.map(function(currentValue,index,arr), thisValue)
其中
callback
为数组中每个元素执行的函数,该函数可接受1-3个参数:
currentvalue
参数表示数组的当前元素项,必须的参数
index
参数表示的当前元素下标,可选参数
arr
参数表示当前元素所属的数组,可选参数
thisValue
表示执行回调函数callback()时的this指向。可选参数。当不写时,则默认是指向window全局
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
2.map和forEach的区别
我们先来看看他们的相同点:
var arr = ['a','b','c','d'];
arr.forEach(function(item,index,arr){
//item表示数组中的每一项,index标识当前项的下标,arr表示当前数组
console.log(item);
console.log(index);
console.log(arr);
console.log(this);
},123); //这里的123参数,表示函数中的this指向,可写可不写,如果不写,则this指向window
arr.map(function(item,index,arr){
//参数含义同forEach
console.log(item);
console.log(index);
console.log(arr);
console.log(this);
},123);
运行之后,可以看出两者参数没有任何的区别,除此之外两者之间还有一个特性,就是不能停止里面的遍历,除非程序报错。
var arr2 = [1, 3, , 13, 2];
var newarr = [];
arr2.map(function (item, index) {
if (arr2[index] == 3) {
arr2.push(14);
arr2.push(5);
}
console.log("数组循环了" + index + "次");
});
console.log(arr2);
map方法同样也不能循环的同时增加数组元素试图改变循环次数。
那他们的区别在哪呢?
- 返回值
var arr = [1, 3, 5, 13, 2];
var res = arr.map(function (item, index) {
item += 1;
return item + 1;
});
console.log(res);
var res2 = arr.forEach(function (item, index) {
item += 1;
return item + 1;
});
console.log(res2);
运行结果:
map方法会返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
forEach方法返回值则永远是undefined。
- 执行速度
jsPref是一个非常好的网站用来比较不同的JavaScript函数的执行速度
由于jsPref网站现在进不去了
我在网上找到了一个其他测试者测试的结果图
可以明显看出forEach()执行的速度相比map慢了70%。