实现对象的 map ,类似 Array.prototype.map 函数
1.
Object.prototype.map = function (fn) {
const obj = this;
const result = {};
for (key in obj) {
if (obj.hasOwnProperty(key)) {
const res = fn(obj[key], key);
result[key] = res;
}
}
return result;
}
2. JSON.stringify 实现
(() => {
Object.prototype._map = function (fn, oThis = null) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} is not a function !`)
}
return JSON.parse(JSON.stringify(this, (key, val) => {
if (key) {
return fn.call(oThis, key, val, this)
} else {
return val
}
}))
}
// 用例
let obj = {
a: 2,
b: 3,
c: 4,
d: 5
};
let _obj = obj._map((key, val, o) => {
return ++val
})
console.log(_obj);
})();
来源整理自:vue3js.cn 面试官系列



