让我们看看 javascript 1.6 -1.8 对数组的扩展 ,并学习如何实现相同的功能 every filter forEach indexOf lastIndexOf map some reduce reduceRight
Array.prototype.every 复制代码 代码如下: if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp*/) { var len = this.length >>> 0; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this && !fun.call(thisp, this[i], i, this)) return false; } return true; }; }
是否数组中的每个元素都通过了callBack的处理?如果是,则返回true,如果有一个不是,则立马返回false 这和我们刚才提到的YUI种的 some 函数 很雷同 :) 功能刚好相反
Array.prototype.filter 复制代码 代码如下: Array.prototype.filter = function (block /*, thisp */) { //过滤器 ,添加方便,进行判断过滤 var values = []; var thisp = arguments[1]; for (var i = 0; i < this.length; i++) if (block.call(thisp, this[i])) values.push(this[i]); return values; };
使用方法 复制代码 代码如下: var val= numbers.filter(function(t){ return t < 5 ; }) alert(val);
下面讲下 ‘ map" 复制代码 代码如下: Array.prototype.map = function(fun /*, thisp*/) { var len = this.length >>> 0; if (typeof fun != "function") throw new TypeError(); var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) res[i] = fun.call(thisp, this[i], i, this); } return res; };
遍历数组,执行函数,迭代数组,每个元素作为参数执行callBack方法,由callBack方法对每个元素进行处理,最后返回处理后的一个数组 var numbers = [1, 4, 9]; var roots = numbers.map(function(a){return a * 2});
Array.prototype.reduce 复制代码 代码如下: Array.prototype.reduce = function(fun /*, initial*/) { var len = this.length >>> 0; if (typeof fun != "function") throw new TypeError(); if (len == 0 && arguments.length == 1) throw new TypeError(); var i = 0; if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i++]; break; } if (++i >= len) throw new TypeError(); } while (true); } for (; i < len; i++) { if (i in this) rv = fun.call(null, rv, this[i], i, this); } return rv; };
让数组元素依次调用给定函数,最后返回一个值,换言之给定函数一定要用返回值
Array.prototype.reduceRight 见名故而思意,从右往左 复制代码 代码如下: Array.prototype.reduceRight = function(fun /*, initial*/) { var len = this.length >>> 0; if (typeof fun != "function") throw new TypeError(); if (len == 0 && arguments.length == 1) throw new TypeError(); var i = len - 1; if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i--]; break; } if (--i < 0) throw new TypeError(); } while (true); } for (; i >= 0; i--) { if (i in this) rv = fun.call(null, rv, this[i], i, this); } return rv; };