首頁 >web前端 >js教程 >尋找數組中的最大數字 - JavaScript

尋找數組中的最大數字 - JavaScript

Susan Sarandon
Susan Sarandon原創
2024-10-08 20:23:29429瀏覽

Find the maximum number in an array - JavaScript

Find the maximum number from an array of positive integers using JavaScript

Solution

//findMaxNumber.js
function findMaxNumber(numbers) {
//Initializes result to track the maximum number, starting at 0.
  let result = 0;

  //Stores the length of the numbers array for use in the loop.
  const numbersLength = numbers.length;

  //Check if the array is not empty before processing it.
  if (numbersLength > 0) {

    //Loops through each number in the array.
    for (let i = 0; i < numbersLength; i++) {

      //Compare each number to the result to check if it's larger.
      if (numbers[i] > result) {

        //Updates result with the current number if it's the largest
        result = numbers[i];
      }
    }
    console.log(result);
    return result;
  }

  return result;
}

findMaxNumber([5, 33, 47, 103]);

Result

> 103

以上是尋找數組中的最大數字 - JavaScript的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn