Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数组中所有元素的总和_Javascript_Arrays_Sum - Fatal编程技术网

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
肯定更简洁。谢谢