区别
map 不能修改原数组,forEach 能改变原数组- map
有 返回值,创建新数组,而forEach无 返回值,返回结果undefined - map和forEach用只能用
try...catch...中断 抛出错误中断,而return不能 ,用其效果相当于for循环的continue会跳过此次循环进入下一次循环。
实现
Array.prototype.forEach = function (callback, context) {
if (this === null) {
throw new TypeError(
"Array.prototype.forEach" + "called on null or undefined"
);
}
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
let arr = this;
let len = arr.length;
for (let i = 0; i < len; i++) {
callback.call(context, arr[i], i, arr);
}
}
Array.prototype.map = function (callback, context) {
if (this === null) {
throw new TypeError(
"Array.prototype.map" + "called on null or undefined"
);
}
if (typeof callback != 'function') {
throw new TypeError(
callback + 'is not a function'
)
}
let arr = Array.prototype.slice.call(this)
let len = arr.length
let arrMap = []
for (let i = 0; i < len; i++) {
arrMap[i] = callback.call(context, arr[i], i, arr)
}
return arrMap
}
|