简体   繁体   中英

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

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;
}

You are passing a set of arguments, but ignoring all but the firt on, which you are attempting to treat as an array.

Pass one argument that actually is an array instead.

var s = new ints([1, 2, 3, 4, 5]);

MOdified code: Changes. Saving all paramaters in an array this.t . Using normal for loop instead of for in as for in will add prototype properties as well.

function ints(t) 
{   
   if(typeof t == 'object'){ // if first argument itself an array.
    this.t = t;   
   }else{
    this.t = Array.prototype.slice.call(arguments, 0);
  } 
}

ints.prototype.sum = function() {
        var sum = 0;           
     console.log(this.t);
        for (var i =0; i<this.t.length; i++) {
                sum += this.t[i];
        }           
        return sum;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM