Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum values using an object? In JavaScript

I have created a function to sum the values but It does not get the result expected, return 0

function ints(t) { this.t=t; }

ints.prototype.sum = function() {
        var sum = 0;
        var value;
        for (var _ in this.t) {
                value = _;
                sum += value;
        }
        return sum;
}

var s = new ints(1, 2, 3, 4, 5);
if (s.sum() !== 15) {
        alert("FAIL: " + s.sum());
}

How to fix it using that object? I want not to use a primitive


1 Answers

If you want to use all the arguments passed to the function, use the arguments object:

function ints(t) {
    this.t = arguments;
}

And in the sum function, iterate over the "array" with a for-in while using the bound variable as an index:

for (var _ in this.t) {
    value = this.t[_];
    sum += value;
}
like image 149
David G Avatar answered Apr 24 '26 11:04

David G