JavaScript生成CC许可链接时变量undefined问题求助
问题排查与修复
核心问题分析
- 变量赋值顺序错误:你先拼接了
link字符串,此时codeShort和codeLong还未被赋值,自然会显示undefined。必须先完成许可码的匹配赋值,再生成链接字符串。 - 无效的字符串分割逻辑:
split(/-{3}/)是按三个连续连字符分割,但输入的许可码都是单个连字符(比如CC-BY),分割后得到的是数组,后续用数组和字符串(如"by")比较永远不成立,导致codeShort和codeLong从未被赋值。 - HTML链接格式错误:原链接字符串里的
href引号未闭合,且>的位置错误,会导致HTML结构无效。
修复后的代码
function generateLicenseLink(licenseCode) { // 处理输入:移除CC-前缀并转为小写 let code = licenseCode.replace("CC-", "").toLowerCase(); let codeShort; let codeLong; // 先根据处理后的code匹配对应的许可信息 if (code === "by") { codeShort = "by"; codeLong = "Creative Commons Attribution License"; } else if (code === "by-nc") { codeShort = "by-nc"; codeLong = "Creative Commons Attribution-NonCommercial License"; } else if (code === "by-sa") { codeShort = "by-sa"; codeLong = "Creative Commons Attribution-ShareAlike License"; } else if (code === "by-nd") { codeShort = "by-nd"; codeLong = "Creative Commons Attribution-NoDerivs License"; } else if (code === "by-nc-sa") { codeShort = "by-nc-sa"; codeLong = "Creative Commons Attribution-NonCommercial-ShareAlike License"; } else if (code === "by-nc-nd") { codeShort = "by-nc-nd"; codeLong = "Creative Commons Attribution-NonCommercial-NoDerivs License"; } else { // 处理未知许可码的兜底逻辑 codeShort = "unknown"; codeLong = "Unknown License"; } // 最后生成格式正确的HTML链接字符串 let link = `<a href="https://creativecommons.org/licenses/${codeShort}/4.0/">${codeLong}</a>`; return link; } // 测试用例 console.log(generateLicenseLink("CC-BY")); console.log(generateLicenseLink("CC-BY-NC")); console.log(generateLicenseLink("CC-BY-SA")); console.log(generateLicenseLink("CC-BY-ND")); console.log(generateLicenseLink("CC-BY-NC-SA")); console.log(generateLicenseLink("CC-BY-NC-ND"));
简洁优化方案(用对象映射替代冗长判断)
function generateLicenseLink(licenseCode) { const code = licenseCode.replace("CC-", "").toLowerCase(); // 许可码与对应信息的映射表 const licenseMap = { "by": { short: "by", long: "Creative Commons Attribution License" }, "by-nc": { short: "by-nc", long: "Creative Commons Attribution-NonCommercial License" }, "by-sa": { short: "by-sa", long: "Creative Commons Attribution-ShareAlike License" }, "by-nd": { short: "by-nd", long: "Creative Commons Attribution-NoDerivs License" }, "by-nc-sa": { short: "by-nc-sa", long: "Creative Commons Attribution-NonCommercial-ShareAlike License" }, "by-nc-nd": { short: "by-nc-nd", long: "Creative Commons Attribution-NonCommercial-NoDerivs License" } }; // 获取匹配的许可信息,无匹配则使用默认值 const license = licenseMap[code] || { short: "unknown", long: "Unknown License" }; return `<a href="https://creativecommons.org/licenses/${license.short}/4.0/">${license.long}</a>`; }
内容的提问来源于stack exchange,提问作者jonooo
相关产品推荐
相关产品推荐

