[js] 数字数组的一点Array Helpers
#1
Object.assign(Array.prototype, { square() { return this.map(n => n * n); }, cube() { return this.map(n => Math.pow(n, 3)); }, sum() { return this.reduce((p, n) => p + n, 0); }, average() { return this.reduce((p, n) => p + n, 0) / this.length; }, even() { return this.filter(n => !(n % 2)); }, odd() { return this.filter(n => n % 2); } });
#2
Array.prototype.square = function() { return this.map(function(n) { return n * n; }); } Array.prototype.cube = function() { return this.map(function(n) { return n * n * n; }); } Array.prototype.sum = function() { return this.reduce(function(a, b) { return a + b; }, 0); } Array.prototype.average = function() { return this.sum() / this.length; } Array.prototype.even = function() { return this.filter(function(item) { return 0 == item % 2; }); } Array.prototype.odd = function() { return this.filter(function(item) { return 0 != item % 2; }); }
#3
Array.prototype.square = function() { var temp = [], l = this.length; for (var i = 0; i < l; i++) { temp[i] = this[i] * this[i]; } //console.log(temp); //console.log(this); return temp; }; Array.prototype.cube = function() { var temp = [], l = this.length; for (var i = 0; i < l; i++) { temp[i] = this[i] * this[i] * this[i]; } //console.log(temp); //console.log(this); return temp; }; Array.prototype.sum = function() { if (this.length === 0) { return NaN; } var temp = 0, l = this.length; for (var i = 0; i < l; i++) { temp += this[i]; } //console.log(temp); //console.log(this); return temp; }; Array.prototype.average = function() { if (this.length === 0) { return NaN; } var l = this.length, temp = this.sum() / l; //console.log(temp); //console.log(this); return temp; }; Array.prototype.even = function() { if (this.length === 0) { return NaN; } var l = this.length, temp = []; for (var i = 0; i < l; i++) { if (!(this[i] % 2)) { temp.push(this[i]); } } //console.log(temp); //console.log(this); return temp; }; Array.prototype.odd = function() { if (this.length === 0) { return NaN; } var l = this.length, temp = []; for (var i = 0; i < l; i++) { if (this[i] % 2) { temp.push(this[i]); } } //console.log(temp); //console.log(this); return temp; };
#test
var numbers = [1, 2, 3, 4, 5]; console.log(numbers.square()); console.log(numbers.cube()); console.log(numbers.sum()); console.log(numbers.average()); console.log(numbers.even()); console.log(numbers.odd()); var empty = []; console.log(empty.average()); console.log(empty.sum());