Array.prototype,map=function(fun){
let arr = [];
this.forEach(function(item, index){ //this指向的是操作的数组 [1,2],.map
arr.push(fun(item, index))
})
return arr ;
}
解读:
所有的数组实例都继承于 Array.prototype,
通过数组的原型对象可以为所有数组对象添加属性
所有的数组方法都定义在 Array.prototype 身上
-
Array.prototype.map:在Array.prototype上增加一个名叫map的方法
-
fun传进来为一个函数
-
声明一个新数组 为map返回一个新数组: let arr=[] return arr
-
使用forEach循环this指向的操作的数组
-
调用fun函数 fun函数为:fun=item=>item*2 或者fun=(item)=>{return item*2 }调用和普通函数一样调用 fun(参数)
使用
let res = [1,2,3].map(item=>tiem*2)