Penso che non c'è nessuno ... ma si può fare uno su JavaScript
Array.prototype.sum = function() {
return (! this.length) ? 0 : this.slice(1).sum() +
((typeof this[0] == 'number') ? this[0] : 0);
};
usano come,
[1,2,3,4,5].sum() //--> returns 15
[1,2,'',3,''].sum() //--> returns 6
[].sum() //--> returns 0
x = [1.2, 3.4, 5.6]
x.sum(); // returns 10.2
Va bene come sottolineato nella commento, puoi anche farlo come metodo non ricorsivo
Array.prototype.sum = function() {
var num = 0;
for (var i = 0; i < this.length; i++) {
num += (typeof this[i] == 'number') ? this[i] : 0;
}
return num;
};
Un altro modo per farlo, attraverso la funzione ..
function sum(arr) {
var num = 0;
for (var i = 0; i < arr.length; i++) {
num += (typeof arr[i] == 'number') ? arr[i] : 0;
}
return num;
};
usarlo come,
sum([1,2,3,4,5]) //--> returns 15
x = [1.2, 3.4, 5.6]
sum(x); // returns 10.2
+1 per 'reduce'. –
Mi piace particolarmente l'uso di ridurre. In qualche modo, non è molto usato, e personalmente ritengo che meriti più acquirenti. +1 – dhruvbird
+1 Wow, davvero conciso. – twneale