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

JavaScript中使用for in循环时数组最后元素计数未更新的问题

数组元素统计结果异常问题分析

问题代码

let array = [1,2,3,3,3,4]

let dict = {}

for (let i in array){
    dict[array[i]] = 0
}

for (let i in array){
    if (array[i] in Object.keys(dict)){
        dict[array[i]]++
    }
}
console.log(dict)

// 预期结果: { '1': 1, '2': 1, '3': 3, '4': 1 }
// 实际结果: { '1': 1, '2': 1, '3': 3, '4': 0 }

问题原因

核心错误出在判断条件if (array[i] in Object.keys(dict)):

  • Object.keys(dict)返回的是字符串数组,此处为['1','2','3','4']
  • 当in运算符作用于数组时,它检查的是数组的索引(下标)是否存在,而非数组元素是否匹配
  • 遍历到元素4时,4 in ['1','2','3','4']实际是检查数组是否存在下标为4的元素,但该数组仅有4个元素,最大下标为3,因此条件不成立,dict[4]未执行自增,保持初始值0

修正方案

方案1:直接检查对象属性存在性

修改判断条件为直接检查元素是否属于dict的属性(in作用于对象时会匹配属性名,数字会自动转为字符串,与dict的键兼容):

for (let i in array){
    if (array[i] in dict){
        dict[array[i]]++
    }
}

方案2:严谨的属性检查(推荐)

使用hasOwnProperty避免继承属性的干扰,更安全:

for (let i in array){
    const key = array[i];
    if (dict.hasOwnProperty(key)){
        dict[key]++
    }
}

方案3:简化统计逻辑(一步完成)

无需提前初始化字典,直接遍历数组时累加计数,代码更简洁高效:

let array = [1,2,3,3,3,4]
let dict = {}

for (let num of array) {
    dict[num] = (dict[num] || 0) + 1
}
console.log(dict) // 输出 { '1': 1, '2': 1, '3': 3, '4': 1 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:13:29