1、forEach的实现
Array.prototype.myForEach = function (callback) {
const len = this.length;
if (len > 0) {
for (let i = 0; i < len; i++) {
callback(this[i], i);
}
}
};
const arr = [1, 2, 3, 4];
arr.myForEach((item, index) => {
console.log(item); // 1,2,3,4
});
2、find的实现
Array.prototype.myFind = function (callback) {
const len = this.length;
const res = null;
if (len > 0) {
for (let i = 0; i < len; i++) {
if (callback(this[i], i) === true) {
return this[i];
}
}
}
return res;
};
const arr = [1, 2, 3, 4];
const findRes = arr.myFind((item) => item > 2);
console.log(findRes); // 3
3、findIndex的实现
Array.prototype.myFindIndex = function (callback) {
const len = this.length;
const res = -1;
if (len > 0) {
for (let i = 0; i < len; i++) {
if (callback(this[i], i) === true) {
return i;
}
}
}
return res;
};
const findIndexRes = arr.myFindIndex((item) => item === 2);
console.log(findIndexRes); // 1
本文暂时没有评论,来添加一个吧(●'◡'●)