数组中所有元素的总和

时间:2016-01-16 18:05:34

标签: javascript arrays sum

我是编程的初学者。我想做一个数组中所有元素的总和。我做了这个,但我看不出我的错误在哪里?

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());

3 个答案:

答案 0 :(得分:6)

this回调中的

forEach是指全局window对象。要设置回调的上下文,请使用Array#forEach第二个参数来传递上下文。

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

&#13;
&#13;
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
&#13;
&#13;
&#13;

如果您正在寻找替代方案,可以使用Array#reduce,此处使用Arrow function

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

&#13;
&#13;
// 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);
&#13;
&#13;
&#13;

答案 1 :(得分:3)

this函数中forEach的引用已更改。将您的代码更新为以下

&#13;
&#13;
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());
&#13;
&#13;
&#13;

以上内容保存了thisthat的引用并将其用于计算。

答案 2 :(得分:1)

最有效的方法是使用reduce数组函数。例如:

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