const arr = [1, 2, 3];
const obj = { a: 1 };
map
Array.prototype.myMap = function (cb) {
// 调用者
const _arr = this;
// this指向
const _arg2 = arguments[1] || window;
const _length = _arr.length;
let res = [];
for (let i = 0; i < _length; i++) {
res.push(cb.apply(_arg2, [_arr[i], i, _arr]));
}
return res;
};
forEach
Array.prototype.myForEach = function (cb) {
const _arr = this;
const _arg2 = arguments[1] || window;
const _length = _arr.length;
for (let i = 0; i < _length; i++) {
cb.apply(_arg2, [_arr[i], i, _arr]);
}
};
filter
Array.prototype.myFilter = function (cb) {
const _arr = this;
const _arg2 = arguments[1] || window;
const _length = _arr.length;
let res = [];
for (let i = 0; i < _length; i++) {
if (cb.apply(_arg2, [_arr[i], i, _arr])) {
res.push(_arr[i]);
}
}
return res;
};
some
Array.prototype.mySome = function (cb) {
const _arr = this;
const _arg2 = arguments[1] || window;
const _length = _arr.length;
let res = false;
for (let i = 0; i < _length; i++) {
if (cb.apply(_arg2, [_arr[i], i, _arr])) {
res = true;
break;
}
}
return res;
};
every
Array.prototype.myEvery = function (cb) {
const _arr = this;
const _arg2 = arguments[1] || window;
const _length = _arr.length;
let res = true;
for (let i = 0; i < _length; i++) {
if (!cb.apply(_arg2, [_arr[i], i, _arr])) {
res = false;
break;
}
}
return res;
};
reduce
Array.prototype.myReduce = function (cb, initialValue) {
const _arr = this;
const _arg2 = arguments[2] || window;
const _length = _arr.length;
for (let i = 0; i < _length; i++) {
initialValue = cb.apply(_arg2, [initialValue, _arr[i], i, _arr]);
}
return initialValue;
};
reduceRight
Array.prototype.myReduceRight = function (cb, initialValue) {
const _arr = this;
const _arg2 = arguments[2] || window;
const _length = _arr.length;
for (let i = _length - 1; i >= 0; i--) {
initialValue = cb.apply(_arg2, [initialValue, _arr[i], i, _arr]);
}
return initialValue;
};