Array.prototype.map = function(fn, thisObj) {
var scope = thisObj || window;
var a = [];
for ( var i=0, j=this.length; i < j; ++i ) {
a.push(fn.call(scope, this[i], i, this));
}
return a;
};
<div>
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
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;
};
复制代码 代码如下:
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
// total == 6
您可能感兴趣的文章: