数组常用方法的实现
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 };