在 JavaScript 中返回数组中的最高值

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 11:24:17

我们需要编写一个 JavaScript 函数,该函数接受一个数字数组。我们的函数应该遍历该数组并从数组中选取最大元素并返回该元素。

示例

其代码为 −

const arr = [5, 3, 20, 15, 7];
const findGreatest = (arr = []) => {
   let greatest = -Infinity;
   if(!arr?.length){
      return null;
   };
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(el < greatest){
         continue;
      };
      greatest = el;
   };
   return greatest;
};
console.log(findGreatest(arr));

输出

控制台中的输出将是 −

20

相关文章


有用资源