使用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
相关产品推荐
相关产品推荐

