陣列找最大值js

在JavaScript中,你可以使用Math.max()函數或者Array.prototype.reduce()方法來找出一個陣列中的最大值。 以下是使用Math.max()函數的示例:

const array = [1, 2, 3, 4, 5];
const max = Math.max(...array);
console.log(max); // Output: 5

這段程式碼將陣列元素拆開並傳遞給Math.max()函數,最後返回最大的數字。 以下是使用Array.prototype.reduce()方法的示例:

const array = [1, 2, 3, 4, 5];
const max = array.reduce((accumulator, current) => {
  return accumulator > current ? accumulator : current;
}, array[0]);
console.log(max); // Output: 5

這個程式碼使用reduce()方法來遍歷陣列中的每個元素,並且比較當前元素與累積器(accumulator)的值。如果當前元素較大,則更新累積器為當前元素。最後,reduce()函數返回最大的數字。