💾arr.max()
💾 replit: arr.max()
Array.prototype.max = function() {
return this.reduce((partialMax, nextValue) => Math.max(partialMax, nextValue));
};
💈範例:
[1,2,3].max(), // 3
[4,2,3].max(), // 4
// [].max(), // ⛔ TypeError: Reduce of empty array with no initial value
雖然使用下列的語法也可以找出數列的最大值,但不能用於太大的陣列。
// 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);
Last updated