直接上代碼
Array.prototype.myForEach = function (callback) {
let arg2 = arguments[1] || window;
for (let i = 0; i < this.length; i++) {
callback.apply(arg2, [this[i], i, this]);
}
};
Array.prototype.myMap = function (callback) {
let arg2 = arguments[1] || window;
let newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(callback.apply(arg2, [this[i], i, this]));
}
return newArr;
};
Array.prototype.myFilter = function (callback) {
let arg2 = arguments[1] || window;
let newArr = [];
for (let i = 0; i < this.length; i++) {
callback.apply(arg2, [this[i], i, this]) ? newArr.push(this[i]) : newArr;
}
return newArr;
};
Array.prototype.myEvery = function (callback) {
let arg2 = arguments[1] || window;
let gate = true;
for (let i = 0; i < this.length; i++) {
if (!callback.apply(arg2, [this[i], i, this])) {
gate = false;
break;
}
}
return gate;
};
Array.prototype.mySome = function (callback) {
let arg2 = arguments[1] || window;
let gate = false;
for (let i = 0; i < this.length; i++) {
if (callback.apply(arg2, [this[i], i, this])) {
gate = true;
break;
}
}
return gate;
};
Array.prototype.myReduce = function (callback, initialValue) {
for (let i = 0; i < this.length; i++) {
initialValue = callback(initialValue, this[i], i, this);
}
return initialValue;
};
Array.prototype.myReduceRight = function (callback, initialValue) {
for (let i = this.length - 1; i >= 0; i--) {
initialValue = callback(initialValue, this[i], i, this);
}
return initialValue;
};
複製代碼