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

JavaScript frequency函数处理两位数数组结果异常问题排查

数字频率统计异常问题分析

你的问题确实和ASCII(准确说是Unicode字符编码)有关,核心原因是对象的键会被自动转为字符串类型,导致后续比较逻辑出错:

  1. 键的类型变化:当你把数字作为对象的键时,JavaScript会自动把它转换成字符串。比如数组里的10会变成对象的键"10",5变成"5"。
  2. 字符串字典序对比:你在判断key > result时,是在做字符串的字典序比较,不是数字大小比较。字典序会逐字符对比编码值:"5"的第一个字符'5'的ASCII码(53)比"10"的第一个字符'1'(49)大,所以"5" > "10"会返回true,最终导致本该选10的时候选了5。

修复方案

把字符串类型的键转回数字后再比较,同时可以把两次遍历合并成一次,提升效率:

const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];

function frequency(array) {
    const countMap = {};
    let maxCount = 0;
    let result = 0;

    // 统计每个数字的出现频率
    for (const num of array) {
        countMap[num] = (countMap[num] || 0) + 1;
    }

    // 一次遍历找到频率最高且数值最大的数字
    for (const [keyStr, val] of Object.entries(countMap)) {
        const num = Number(keyStr);
        // 两种情况更新结果:频率更高,或者频率相同但数字更大
        if (val > maxCount || (val === maxCount && num > result)) {
            maxCount = val;
            result = num;
        }
    }

    return [result, maxCount];
}

const [res, count] = frequency(numArr);
console.log(`number with highest freq: ${res}\nfrequency: ${count}`)

运行修复后的代码,numArr的输出会正确返回10(频率3)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:07:07