如何用JavaScript获取二维无序数组各子数组的最大元素
解决二维数组提取子数组最大值的问题
你遇到的问题大概率是没有正确收集每个子数组的最大值,而是每次循环都覆盖了结果变量,导致最终只保留了最后一个子数组的最大值。
错误示例(可能的问题代码)
比如以下代码就会只返回最后一个子数组的最大值:
const arr = [[-34, -54, -74], [-32, -2, -65], [-54, 7, -43]]; let maxValues; for (let i = 0; i < arr.length; i++) { // 每次循环都覆盖maxValues,而非添加新元素 maxValues = Math.max(...arr[i]); } console.log(maxValues); // 输出7
正确解法
方法1:使用map方法(最简洁)
map方法会遍历数组并返回新数组,正好适配这个需求:
const arr = [[-34, -54, -74], [-32, -2, -65], [-54, 7, -43]]; const maxValues = arr.map(subArr => Math.max(...subArr)); console.log(maxValues); // 输出 [-34, -2, 7]
原理:对每个子数组subArr,用Math.max(...subArr)展开子数组元素取最大值,最终所有最大值组成新数组。
方法2:使用forEach循环收集结果
初始化一个空数组,遍历每个子数组时将最大值推入数组:
const arr = [[-34, -54, -74], [-32, -2, -65], [-54, 7, -43]]; const maxValues = []; arr.forEach(subArr => { maxValues.push(Math.max(...subArr)); }); console.log(maxValues); // 输出 [-34, -2, 7]
方法3:使用普通for循环
如果习惯用传统循环,确保每次将最大值添加到结果数组中:
const arr = [[-34, -54, -74], [-32, -2, -65], [-54, 7, -43]]; const maxValues = []; for (let i = 0; i < arr.length; i++) { const currentMax = Math.max(...arr[i]); maxValues.push(currentMax); } console.log(maxValues); // 输出 [-34, -2, 7]
内容的提问来源于stack exchange,提问作者Semir Sisic
相关产品推荐
相关产品推荐

