手写 Array.prototype.map
题目:实现一个
myMap,等价于原生Array.prototype.map。
Array.prototype.myMap = function (fn, context) {
const arr = [].slice.call(this);
const resArr = [];
for (let i = 0; i < arr.length; i++) {
if (!arr.hasOwnProperty(i)) {
// 稀疏数组:跳过缺失的下标
continue;
}
resArr.push(fn.call(context, arr[i], i, this));
}
return resArr;
};
补充
补充:原生
map在遇到稀疏数组(empty)时 会保留空洞,而普通forEach也会跳过空洞。这里用hasOwnProperty过滤后再调用回调,行为更接近原生forEach/map对稀疏数组的处理。如果不在意稀疏数组,可以直接
for循环逐项push即可。



