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

使用JavaScript开发RGB转HEX转换器运行失败,请问代码存在什么问题?

代码错误点

  • 核心错误:ColorToHex 函数的else分支缺少return语句,当颜色值处于0~255区间时,函数无返回值默认返回undefined,最终拼接的转换结果不符合预期。
  • 规范问题:r、g、b、res变量均未使用let/const声明,会意外泄漏为全局变量,可能引发其他逻辑冲突。
  • 结构问题:嵌套的rgb函数没有返回值,仅通过全局变量传递转换结果,代码结构冗余不合理。

修正后代码

function convert() {
    // 声明变量避免全局泄漏
    const r = parseInt(document.getElementById('r').value);
    const g = parseInt(document.getElementById('g').value);
    const b = parseInt(document.getElementById('b').value);

    // 提取通用转换逻辑,直接返回结果避免依赖全局变量
    function colorToHex(color) {
        if (color > 255) return "FF";
        if (color < 0) return "00";
        // 补全return语句
        return color.toString(16).padStart(2, "0").toUpperCase();
    }
    
    const res = colorToHex(r) + colorToHex(g) + colorToHex(b);
    document.getElementById('result').innerHTML = res;    
    return false;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:06:05