一. 定义
**map()**
方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
二. 用法
**map()**
方法按照原始数组元素顺序依次处理元素。
注意:
**map()**
不会对空数组进行检测。**map()**
不会改变原始数组。三. 手写代码
Array.prototype.newMap = function (fn) {
let arr = this;
let result = [];
for(let i=0; i<arr.length; i++){
result[i] = fn(arr[i]);
}
return result;
}
四. 测试代码
const arr = [1, 2, 3, 4];
console.log(arr.map(item => item*2)); // [ 2, 4, 6, 8 ]
console.log(arr.newMap(item => item*2)); // [ 2, 4, 6, 8 ]