语法:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

参数:

callback

生成新数组元素的函数,使用三个参数:

currentValue

callback 数组中正在处理的当前元素。

index 可选

callback 数组中正在处理的当前元素的索引。

array 可选

map 方法调用的数组。

thisArg 可选

执行 callback 函数时值被用作this

返回值:

一个由原数组每个元素执行回调函数的结果组成的新数组

实现:

Array.prototype.map = function(callback, thisArg) {
	if (this == undefined) {
    throw new TypeError('this is null or not defined')
  }
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function')
  }
  const res = []
  const O = Object(this)
  const len = O.length >>> 0;
  for (let i = 0; i < len; i++) {
    if (i in O) {
      // 调用回调函数并传入新数组
      res[i] = callback.call(thisArg, O[i], i, this)
    }
  }
  return res
}