数组map 方法
Array.prototype.map(callback[,thisArg]);
【功能】
依次迭代数组中的元素,在callback中处理后,返回一个新的数组;
forEach和map一样,都会依次迭代数组中的元素,不同的是forEach
并不会返回一个新数组,而map会返回一个新的数组;
map 接受两个参数,第一个是回调函数,第二个控制回调函数中this的指向;
1.callback(item,index,arr);
接受3个参数,第一个‘item’,为当前迭代的数组中的元素,‘index’为当前迭代元素的下标,‘arr’为原数组;
2.thisArg
默认callback中的this是指向window的,可以通过设置every的第二个参数,改变callback中this的指向;
3.案例
let new_arr = [1,2,6,3,4,5];
let res = new_arr.map(function(item,index,arr){
console.log(this); //window
return item+1;
});
console.log(res);//[2, 3, 7, 4, 5, 6]
该案例中,数组中每个元素都会+1,并插入到新的数组中,最后返回一个新数组。
其中只设置了every的第一个参数,没有设置第二个参数,因此第一个参数(callback会回调函数)中的this会指向window对象。
let new_arr = [1,2,6,3,4,5];
let res = new_arr.every(function(item,index,arr){
console.log(this); //new_arr
return item+1;
},new_arr);
console.log(res);//[2, 3, 7, 4, 5, 6]
由于设置了第二个参数,因此会更改回调函数中的this指向,此时this指向new_arr;