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

JavaScript基础代码输出出现undefined,求原因及解决方法

问题原因与解决办法

你看到的undefined是因为两个原因叠加:

  1. 你的函数mostFrequentItemCount内部用console.log(d)输出了正确结果5,但函数本身没有通过return语句返回任何值,JavaScript中没有返回值的函数默认返回undefined。
  2. 你在调用函数时又套了一层console.log,也就是console.log(mostFrequentItemCount(...)),这行代码会先执行函数内部的console.log(d)输出5,然后打印函数的返回值undefined。

修复方案

方案一:去掉外部的console.log

直接调用函数即可,因为函数内部已经负责打印结果:

function mostFrequentItemCount(collection){
    let a, b, c = 0, d = 0; 
    collection.sort((a,b) => a - b)
   
    for (i=0; i<collection.length; i++){
        if (collection[i] == collection[i-1]){
            b = a = a + 1;
            if (b > d){ // 修正原代码逻辑,直接和当前最大次数d比较
                d = b
            }
        } else {
            b = a; 
            a = 1
        }
    } 
    console.log(d)
} 
// 直接调用,不再套console.log
mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3])

方案二:让函数返回结果,外部统一打印(更规范)

这种写法符合函数的单一职责,函数只负责计算结果,打印交给外部:

function mostFrequentItemCount(collection){
    // 处理空数组的边界情况
    if (collection.length === 0) return 0;
    
    let currentCount = 1;
    let maxCount = 1;
    collection.sort((a,b) => a - b);
   
    // 从i=1开始,避免i=0时访问collection[-1]的问题
    for (let i = 1; i < collection.length; i++){
        if (collection[i] === collection[i-1]){
            currentCount++;
            if (currentCount > maxCount){
                maxCount = currentCount;
            }
        } else {
            currentCount = 1;
        }
    } 
    // 返回计算好的最大次数
    return maxCount;
} 
// 打印函数返回的结果
console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))

额外优化提示

原代码还有两处可以优化的细节:

  • 循环从i=0开始时,collection[i-1]会取到undefined,虽然不会报错,但逻辑上从i=1开始更合理,直接和前一个有效元素比较。
  • 原代码中的if (b>(c && d))逻辑有问题,c是索引值,这里只需要和记录最大次数的d比较即可,不需要引入索引c。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:05:23