Reputation:
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
Upvotes: 3
Views: 1694
Reputation: 23208
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());
}
Upvotes: 0
Reputation: 96810
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;
}
Upvotes: 1
Reputation: 943562
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]);
Upvotes: 0