手写实现对象的map方法
要求原对象:
obj={
name:'zhou',
age:'21'
}
遍历之后输出的新对象:
obj={
name:'zhou1',
age:'211'
}
实现代码:
//要遍历的对象
let obj={
name:'zhou',
age:'21'
}
console.log(obj)
//方法1
Object.prototype.myMap=function(fn){
//this是obj对象
var keys=Object.keys(this)
var that=this;
var newObj={};
keys.forEach(function(key,index){
// console.log(that[key])
newObj[key]=fn(that[key],key)
})
// console.log(keys)
return newObj;
}
var newObj=obj.myMap(function(value,key){
return value+'1'
})
console.log(newObj)