# arr.max()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit: arr.max()

```javascript
Array.prototype.max = function() {
    return this.reduce((partialMax, nextValue) => Math.max(partialMax, nextValue));
};
```

💈範例：

```javascript
[1,2,3].max(),    // 3
[4,2,3].max(),    // 4
// [].max(),      // ⛔ TypeError: Reduce of empty array with no initial value
```

{% endtab %}

{% tab title="🧨 雷區" %}
雖然使用下列的語法也可以找出數列的最大值，但不能用於太大的陣列。

```javascript
// both spread (...) and `apply` will either fail or return the wrong result 
// if the array has too many elements, because they try to pass the array 
// elements as function parameters. 
const arr = [1, 2, 3];
const max = Math.max(...arr);
const max = Math.max.apply(null, arr);
```

{% endtab %}

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

* [Math.max()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) ⟩ [Getting the maximum element of an array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max#getting_the_maximum_element_of_an_array)
  {% endtab %}

{% tab title="Untitled" %}

* [Is there a max number of arguments JavaScript functions can accept?](https://stackoverflow.com/questions/22747068/is-there-a-max-number-of-arguments-javascript-functions-can-accept)
  {% endtab %}
  {% endtabs %}
