数组中所有元素的总和

编程入门 行业动态 更新时间:2024-10-19 22:20:51
本文介绍了数组中所有元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am a beginner in programming. I want to do the sum of all elements in an array. I made this but I can't see where are my mistakes?

function ArrayAdder(_array) { this.sum = 0; this.array = _array || []; } ArrayAdder.prototypeputeTotal = function () { this.sum = 0; this.array.forEach(function (value) { this.sum += value; }); return this.sum; }; var myArray = new ArrayAdder([1, 2, 3]); console.log(myArrayputeTotal());

在 forEach 回调中的

推荐答案

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

this inside the forEach callback refers to the global window object. To set the context of the callback, use the Array#forEach second argument to pass the context.

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.prototypeputeTotal = 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(myArrayputeTotal()); document.write(myArrayputeTotal()); // For Demo purpose

如果您正在寻找替代方法,则可以使用 Array#reduce ,此处与箭头功能

If you're looking for an alternative, you can use Array#reduce, here using with 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);

更多推荐

数组中所有元素的总和

本文发布于:2023-10-24 19:58:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524860.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!