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

如何用JavaScript的for of循环获取数组最值?最大值无法更新求解

问题分析与解决:for...of循环获取数组最值的错误修复

你的代码核心问题是混淆了for...of循环的变量含义:

  • for (let i of arr)里的i是数组的元素值,不是索引,所以你用arr[i]去取值完全错误,这直接导致最大值判断逻辑失效,最小值偶尔看似正确只是巧合。

修复后的代码:

const arr = '2 3 1 1 8'.split(" ").map(Number)
let small = arr[0]
let big = arr[0]
// 把变量名改成num更直观,避免和索引混淆
for (let num of arr) {
  if (big < num) {
    big = num
  }
  if (small > num) {
    small = num
  }
}
console.log(small, big) // 输出 1 8

如果不需要手动实现循环,也可以用更简洁的方式:

const arr = '2 3 1 1 8'.split(" ").map(Number)
const small = Math.min(...arr)
const big = Math.max(...arr)
console.log(small, big)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:27:39