原始物件 新增方法...順便加強 map() reduce() filter()運用
續前篇:
這次的挑戰是:
要替一個陣列物件新增以下幾個方法 ..
square,cube,sum,average,even,odd (實作上大致上就如方法所述)
預備開始-
var numbers = [1, 2, 3, 4, 5];
Array.prototype.square = function () {
return this.map((value, index) =>Math.pow(parseInt(value), 2));
};
Array.prototype.cube = function () {
return this.map((value, index) =>Math.pow(parseInt(value), 3));
}
Array.prototype.sum = function () {
return this.reduce((prev, current) =>prev + current);
}
Array.prototype.average = function () {
return this.length>0?
this.reduce((prev, current) =>prev + current) / this.length:'NaN';
}
Array.prototype.even = function () {
return this.filter((element) =>element % 2 == 0);
}
Array.prototype.odd = function () {
return this.filter((element) =>element % 2 != 0);
}
小心得:這次的關鍵是 要在原生Array物件原型直接加入新方法...順便把map reduce 加上filter再加強一下^_^