这些方法假定原数组内都是数字类型。
这篇博文用来复习ES5中的,像数组的map,reduce,filter方法特性。
//返回所有数平方的数组
Array.prototype.square = function(){
return this.map(function(e){return e * e;});
};
//返回所有数立方的数组
Array.prototype.cube = function(){
return this.map(function(e){return Math.pow(e, 3);});
};
//返回所有数之和
Array.prototype.sum = function(){
return this.reduce(function(prev,cur){return prev + cur;}, 0);
};
//返回所有数的平均数
Array.prototype.average = function(){
return this.sum() / this.length;
};
//找出数组内的偶数
Array.prototype.even = function(){
return this.filter(function(e){return e % 2 === 0});
};
//找出数组内的奇数
Array.prototype.odd = function(){
return this.filter(function(e){return e % 2 !== 0});
};