Javascript 数组中所有元素的总和
我是编程的初学者。我想对数组中的所有元素求和。我犯了这个,但我看不出我的错误在哪里Javascript 数组中所有元素的总和,javascript,arrays,sum,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
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());
此
的引用在forEach
函数中更改。将代码更新为以下内容
函数数组加法器(\u数组){
此值为0.sum=0;
this.array=_array | |[];
}
ArrayAdder.prototype.computeTotal=函数(){
此值为0.sum=0;
var=这个;
this.array.forEach(函数(值){
即:总和+=数值;
});
返回此.sum;
};
var myArray=newarrayadder([1,2,3]);
log(myArray.computeTotal())
此在forEach
回调中引用全局窗口
对象。要设置回调的上下文,请使用第二个参数传递上下文
this.array.forEach(function (value) {
this.sum += value;
}, this); // <-- `this` is bound to the `forEach` callback.
最有效的方法是使用数组函数。例如:
this.array = [0, 1, 2, 3]
this.sum = this.array.reduce(function(a, b) {
return a + b;
});
相关:……正如我链接的问题中所发现的。。。但这并不能回答这个问题。然而,使用reduce绝对是解决这个问题最惯用的方法。它可能需要询问者重写一些代码,但肯定更有效。使用reduce
肯定更简洁。谢谢