专业的编程技术博客社区

网站首页 > 博客文章 正文

JavaScript数组forEach、find和findIndex方法的实现

baijin 2024-08-23 10:29:08 博客文章 7 ℃ 0 评论

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

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表