supongo que no hay nada ... pero se puede hacer uno por javascript
Array.prototype.sum = function() {
return (! this.length) ? 0 : this.slice(1).sum() +
((typeof this[0] == 'number') ? this[0] : 0);
};
lo utilizan como,
[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
bien como se ha señalado en el comente, también puede hacerlo de manera no recursiva
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;
};
Otra manera de hacerlo, a través de la función ..
function sum(arr) {
var num = 0;
for (var i = 0; i < arr.length; i++) {
num += (typeof arr[i] == 'number') ? arr[i] : 0;
}
return num;
};
utilizarlo como,
sum([1,2,3,4,5]) //--> returns 15
x = [1.2, 3.4, 5.6]
sum(x); // returns 10.2
+1 para 'reducir'. –
Me gusta especialmente el uso de reducir. De alguna manera, no se usa mucho, y personalmente siento que merece más tomadores. +1 – dhruvbird
+1 Guau, muy conciso. – twneale