javascript - Sum of all elements in an array -


i beginner in programming. want sum of elements in array. made can't see 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()); 

this inside foreach callback refers global window object. set context of callback, use array#foreach second argument pass context.

this.array.foreach(function (value) {     this.sum += value; }, this); // <-- `this` bound `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()); // demo purpose


if you're looking alternative, can use array#reduce, here using arrow function

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

// note: if doesn't work in browser,  // check in latest version of chrome/firefox    var arr = [1, 2, 3];  var sum = arr.reduce((x, y) => x + y);    document.write(sum);


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -