zoukankan      html  css  js  c++  java
  • js数组方法forEach,map,filter,every,some实现

    数组常用方法的实现

     1 Array.prototype.map = function(fun /*, thisp*/)
     2 {
     3   var len = this.length;
     4   if (typeof fun != "function")
     5     throw new TypeError();
     6 
     7   var res = new Array(len);
     8   var thisp = arguments[1];
     9   for (var i = 0; i < len; i++)
    10   {
    11     if (i in this)
    12       res[i] = fun.call(thisp, this[i], i, this);
    13   }
    14 
    15   return res;
    16 };
    17 
    18 Array.prototype.filter = function(fun /*, thisp*/)
    19 {
    20   var len = this.length;
    21   if (typeof fun != "function")
    22     throw new TypeError();
    23 
    24   var res = new Array();
    25   var thisp = arguments[1];
    26   for (var i = 0; i < len; i++)
    27   {
    28     if (i in this)
    29     {
    30       var val = this[i]; // in case fun mutates this
    31       if (fun.call(thisp, val, i, this))
    32         res.push(val);
    33     }
    34   }
    35 
    36   return res;
    37 };
    38 
    39 Array.prototype.some = function(fun /*, thisp*/)
    40 {
    41   var len = this.length;
    42   if (typeof fun != "function")
    43     throw new TypeError();
    44 
    45   var thisp = arguments[1];
    46   for (var i = 0; i < len; i++)
    47   {
    48     if (i in this && fun.call(thisp, this[i], i, this))
    49       return true;
    50   }
    51 
    52   return false;
    53 };
    54 
    55 Array.prototype.every = function(fun /*, thisp*/)
    56 {
    57   var len = this.length;
    58   if (typeof fun != "function")
    59     throw new TypeError();
    60 
    61   var thisp = arguments[1];
    62   for (var i = 0; i < len; i++)
    63   {
    64     if (i in this && !fun.call(thisp, this[i], i, this))
    65     return false;
    66   }
    67 
    68   return true;
    69 };
    70 
    71 Array.prototype.forEach = function(fun /*, thisp*/)
    72 {
    73   var len = this.length;
    74   if (typeof fun != "function")
    75     throw new TypeError();
    76 
    77   var thisp = arguments[1];
    78   for (var i = 0; i < len; i++)
    79   {
    80     if (i in this)
    81       fun.call(thisp, this[i], i, this);
    82   }
    83 };
  • 相关阅读:
    JS 百度地图路书---动态路线
    jQuery---创建和添加节点
    CSS基础
    第一篇:前端知识之HTML内容
    JS高级---为内置对象添加原型方法
    JS DOM属性+JS事件
    Vue-router
    vue使用kkfileview文件预览功能
    JS高级---案例:验证密码的强度
    promise是怎么来的?
  • 原文地址:https://www.cnblogs.com/xfcao/p/12979037.html
Copyright © 2011-2022 走看看