Array.prototype.map

手写Array.prototype.map

    Array.prototype.my_map = function (fn, context) {
      if (Object.prototype.toString.call(fn) != "[object Function]") {
        throw new TypeError(fn + " is not a function");
      }
      const ctx = context ? context : this;
      const thisArray = this;
      let resArr = []
      for (var i = 0; i < thisArray.length; i++) {
        resArr.push(fn.call(ctx, thisArray[i], i, thisArray));
      }
      return resArr // 返回map后的数组
    }

    // 测试用例
    var a = [1, 2, 3];
    var b = a.my_map(function (val, index) {
      return val + 1;
    })
    console.log(b);

手写Array.prototype.forEach

    Array.prototype.my_forEach = function (fn, context) {
      if (Object.prototype.toString.call(fn) != "[object Function]") {
        throw new TypeError(fn + " is not a function");
      }
      const ctx = context ? context : this;
      const thisArray = this;
      for (var i = 0; i < thisArray.length; i++) {
        fn.call(ctx, thisArray[i], i, thisArray)
      }
    }

手写Array.prototype.some

    Array.prototype.my_some = function (fn, context) {
      if (Object.prototype.toString.call(fn) != "[object Function]") {
        throw new TypeError(fn + " is not a function");
      }
      const ctx = context ? context : this;
      const thisArray = this;
      for (var i = 0; i < thisArray.length; i++) {
        const result = fn.call(ctx, thisArray[i], i, thisArray);
        if (result) return true
      }
      return false
    }

手写Array.prototype.every

    Array.prototype.my_every = function (fn, context) {
      if (Object.prototype.toString.call(fn) != "[object Function]") {
        throw new TypeError(fn + " is not a function");
      }
      const ctx = context ? context : this;
      const thisArray = this;
      for (var i = 0; i < thisArray.length; i++) {
        const result = fn.call(ctx, thisArray[i], i, thisArray);
        if (!result) return false
      }
      return true
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容