The sum of all elements in the array

I'm starting to program. I want to make the sum of all the elements in an array. I did it, but I don’t see where my errors are?

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());
+4
source share
3 answers

thisinside a callback forEachrefers to a global object window. To set the callback context, use the second argument Array#forEachto 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
Run codeHide result

If you are looking for an alternative you can use Array#reduceusing the 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);
Run codeHide result
+6
source

The link thishas changed in function forEach. Update your code to the following

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

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

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

this that .

+3

- reduce. :

this.array = [0, 1, 2, 3]
this.sum = this.array.reduce(function(a, b) {
  return a + b;
});
0

Source: https://habr.com/ru/post/1624601/


All Articles