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 };
  • 相关阅读:
    37.leetcode11_container_with_most_water
    36.leetcode8_string_to_integer
    34.leetcode15&5_time_limit_exceeded
    35.leetcode15_3Sum
    33.leetcode6_zigzag_conversion
    32.leetcode3_longest_substring_without_repeating_characters
    31.leetcode2_add_two_numbers
    29.leetcode172_factorial_trailing_zeroes
    30.leetcode171_excel_sheet_column_number
    [LeetCode] 43.Multiply Strings 字符串相乘
  • 原文地址:https://www.cnblogs.com/xfcao/p/12979037.html
Copyright © 2011-2022 走看看