我是编程的初学者。我想做一个数组中所有元素的总和。我做了这个,但我看不出我的错误在哪里?
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
回调中的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
如果您正在寻找替代方法,则可以使用
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);