Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 25503  / 9 Years ago, sat, january 16, 2016, 12:00:00

I am a beginner in programming. I want to do the sum of all elements in an array. I made this but I can't see where are my mistakes?



function ArrayAdder(_array) {
this.sum = 0;
this.array = _array || [];
}

ArrayAdder.prototype.computeTotal = function () {
this.sum = 0;
this.array.forEach(function (value) {
this.sum += value;
});
return this.sum;
};

var myArray = new ArrayAdder([1, 2, 3]);
console.log(myArray.computeTotal());

More From » arrays

 Answers
34

this inside the forEach callback refers to the global window object. To set the context of the callback, use the Array#forEach second argument to pass the context.



this.array.forEach(function (value) {
this.sum += value;
}, this); // <-- `this` is bound to the `forEach` callback.




function ArrayAdder(_array) {
this.sum = 0;
this.array = _array || [];
}

ArrayAdder.prototype.computeTotal = function () {
this.sum = 0;
this.array.forEach(function (value) {
this.sum += value;
}, this);
return this.sum;
};

var myArray = new ArrayAdder([1, 2, 3]);

console.log(myArray.computeTotal());
document.write(myArray.computeTotal()); // For Demo purpose








If you're looking for an alternative, you can use Array#reduce, here using with Arrow function



var sum = arr.reduce((x, y) => x + y);




// Note: If this doesn't work in your browser,
// check in the latest version of Chrome/Firefox

var arr = [1, 2, 3];
var sum = arr.reduce((x, y) => x + y);

document.write(sum);




[#63697] Friday, January 15, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcos

Total Points: 331
Total Questions: 106
Total Answers: 104

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;