首页 >web前端 >js教程 >查找数组中的最大数字 - JavaScript

查找数组中的最大数字 - JavaScript

Susan Sarandon
Susan Sarandon原创
2024-10-08 20:23:29406浏览

Find the maximum number in an array - JavaScript

使用 JavaScript 从正整数数组中查找最大数字

解决方案

//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]);

结果

> 103

以上是查找数组中的最大数字 - JavaScript的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn