美文网首页
Array.prototype.map

Array.prototype.map

作者: 技术体验师_萦回 | 来源:发表于2021-06-11 14:50 被阅读0次

    手写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
        }
    

    相关文章

      网友评论

          本文标题:Array.prototype.map

          本文链接:https://www.haomeiwen.com/subject/amveeltx.html