我是编程的初学者。我想做一个数组中所有元素的总和。我做了这个,但我看不出我的错误在哪里?
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());
答案 0 :(得分:6)
this
回调中的 forEach
是指全局window
对象。要设置回调的上下文,请使用Array#forEach
第二个参数来传递上下文。
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
&#13;
如果您正在寻找替代方案,可以使用Array#reduce
,此处使用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);
&#13;
答案 1 :(得分:3)
this
函数中forEach
的引用已更改。将您的代码更新为以下
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;
以上内容保存了this
中that
的引用并将其用于计算。
答案 2 :(得分:1)
最有效的方法是使用reduce数组函数。例如:
this.array = [0, 1, 2, 3]
this.sum = this.array.reduce(function(a, b) {
return a + b;
});