# arr.sum(), .average()

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [objects](https://lochiwei.gitbook.io/web/js/val/obj) ⟩ [Array](https://lochiwei.gitbook.io/web/js/val/builtin/arr) ⟩ [methods](https://lochiwei.gitbook.io/web/js/val/builtin/arr/method) ⟩ sum(), average()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit: [arr.sum()](https://replit.com/@pegasusroe/arrsum#index.js)

```javascript
// 🔸 arr.sum()
Array.prototype.sum = function(){
    return this.reduce((result, value) => result + value, 0);
};

// 🔸 arr.average()
Array.prototype.average = function(){
    return this.sum() / this.length;
};
```

💈範例：

```javascript
[1,2,3].sum(),        // 6
[].sum(),             // 0
[1,2,3].average(),    // 2
```

{% endtab %}

{% tab title="📘 手冊" %}

* [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
  {% endtab %}

{% tab title="🗣 討論" %}

* [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers)
  {% endtab %}

{% tab title="⬇️ 應用" %}

* [guo-zhong-cheng-ji-yi-lan-biao](https://lochiwei.gitbook.io/web/appendix/gas/projects/guo-zhong-cheng-ji-yi-lan-biao "mention")
  {% endtab %}
  {% endtabs %}
