语法
Map
作用是生成一个新数组,遍历原数组,将每个元素拿出来做一些变换然后 append
到新的数组中。
[1, 2, 3].map((v) => v + 1)
// -> [2, 3, 4]
Map
有三个参数,分别是当前索引元素,索引,原数组
['1','2','3'].map(parseInt)
// parseInt('1', 0) -> 1
// parseInt('2', 1) -> NaN
// parseInt('3', 2) -> NaN
array.map(function(currentValue,index,arr), thisValue)
-
function(currentValue, index,arr)
必须。函数,数组中的每个元素都会执行这个函数 函数参数:
currentValue | 必须。当前元素的值 |
---|---|
index | 可选。当前元素的索引值 |
arr | 可选。当前元素属于的数组对象 |
- thisValue
可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。
如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。
简单示例
数组中的每个元素乘于输入框指定的值,并返回新数组:
var numbers = [65, 44, 12, 4];
let result = numbers.map((num)=>(num*10));
console.log(result); //650,440,120,40
实现
- 可以看做是队列操作
- 新建一个队列,不断从原来的数组(队列头)中拿元素,计算后放入新队列中
- 返回新队列
Array.prototype.myMap = function (func, currentElement) {
if (typeof func !== "function") {
throw new TypeError(`${func} is not a function`);
}
let arr = this;
let result = new Array();
for (let i = 0; i < arr.length; i++) {
// 迭代执行
let tmp = func.call(currentElement, arr[i], i, arr);
result.push(tmp);
}
return result;
}
let numbers = [65, 44, 12, 4];
let result = numbers.myMap(
(num, index) => {
console.log(index);
return num * 10
}
);
console.log(result);