Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
Object.defineProperty(Object.prototype, 'sum', {
enumerable:false,
value:function() {
var t=0;for(var i in this)
if (!isNaN(this[i]))
t+=this[i];
return t;
}
});
[20,25,27.1].sum() // 72.1
[10,"forty-two",23].sum() // 33
[Math.PI,0,-1,1].sum() // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255
o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum()); // 53.519999999999996