You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用JavaScript函数找出嵌套数组中的最大值?

解决嵌套数组的最大值查找问题

没问题,我来帮你搞定这个嵌套数组找最大值的需求~你的数组里包含了子数组,直接用普通的Math.max会因为子数组无法被识别为数字而返回NaN,所以我们需要先处理嵌套结构,再找最大值。下面给你几种可行的JavaScript解决方案:

方法1:使用ES6的Array.flat()快速扁平化数组

如果你的运行环境支持ES2019及以上(比如现代浏览器、Node.js 11+),可以直接用flat(Infinity)把所有嵌套层级的数组展开成一维,再用Math.max取最大值:

function largestNumber(arr) {
  // 展开所有嵌套层级的数组
  const flattenedArr = arr.flat(Infinity);
  // 用扩展运算符把数组元素传入Math.max
  return Math.max(...flattenedArr);
}

// 测试你的示例数组
console.log(largestNumber([1,19,[3,7],16,[19,27,12],13,11])); // 输出 27

方法2:递归实现扁平化(兼容旧环境)

如果需要兼容不支持flat的旧环境,可以自己写一个递归函数来扁平化数组:

// 递归扁平化数组的工具函数
function flattenNestedArray(arr) {
  let result = [];
  for (const item of arr) {
    // 如果当前元素是数组,递归处理后合并到结果
    if (Array.isArray(item)) {
      result = result.concat(flattenNestedArray(item));
    } else {
      // 非数组元素直接加入结果
      result.push(item);
    }
  }
  return result;
}

function largestNumber(arr) {
  const flattenedArr = flattenNestedArray(arr);
  return Math.max(...flattenedArr);
}

console.log(largestNumber([1,19,[3,7],16,[19,27,12],13,11])); // 输出 27

方法3:递归遍历直接跟踪最大值(更高效)

如果不想额外创建扁平化数组,可以在递归遍历的时候直接记录当前最大值,这样更节省内存,适合处理大型嵌套数组:

function largestNumber(arr) {
  let maxValue = -Infinity;

  // 递归遍历数组的内部函数
  function traverseElements(current) {
    for (const item of current) {
      if (Array.isArray(item)) {
        // 遇到子数组就继续递归遍历
        traverseElements(item);
      } else {
        // 遇到数字就比较并更新最大值
        if (item > maxValue) {
          maxValue = item;
        }
      }
    }
  }

  traverseElements(arr);
  return maxValue;
}

console.log(largestNumber([1,19,[3,7],16,[19,27,12],13,11])); // 输出 27

这三种方法都能完美解决你的问题,你可以根据自己的运行环境和需求选择合适的方案~

内容的提问来源于stack exchange,提问作者Neeraj Prasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:31:16