我尝试创建一个函数,它接受一个许可证代码,然后返回一个link元素,其中包含正确的许可证代码和描述,我似乎找不出代码中哪里出错了,但我猜是if语句。
这是我得到的
function generateLicenseLink(licenseCode) {
let code = licenseCode.replace("CC-", "").toLowerCase();
let codeToTest = code.split(/-{3}/);
let test = codeToTest;
let codeShort;
let codeLong;
let link = `<a href ="https://creativecommons.org/licenses/${codeShort}/4.0/>${codeLong}</a>`;
if (test === "by") {
codeShort = "by";
codeLong = "Creative Commons Attribution License";
}
else if (test === "by-nc") {
codeShort = "by-nc";
codeLong = "Creative Commons Attribution-NonCommercial License";
}
else if (test === "by-sa") {
codeShort = "by-sa";
codeLong = "Creative Commons Attribution-ShareAlike License";
}
else if (test === "by-nd") {
codeShort = "by-nd";
codeLong = "Creative Commons Attribution-NoDerivs License";
}
else if (test === "by-nd-sa") {
codeShort = "by-nd-sa";
codeLong = "Creative Commons Attribution-NonCommercial-ShareAlike License";
}
else if (test === "by-nc-nd") {
codeShort = "by-nc-nd";
codeLong = "Creative Commons Attribution-NonCommercial-NoDerivs License";
}
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"));
我想要返回的内容如下所示:'Creative Commons Attribution-NonCommercial License'
谢谢大家!
我试过用switch语句代替if语句,试过用不同的方式格式化URL,试过替换"CC-"并在不同的位置拆分元素,但在变量部分都显示为未定义,如下所示:
未定义https://creativecommons.org/licenses/undefined/4.0/>undefined
2条答案
按热度按时间fiei3ece1#
操作顺序错误
lyr7nygr2#
当你创建一个插值字符串时,
${}
中的值会被立即计算,当你以后使用该字符串时,它们不会被“记住”。在你定义link
时,codeShort
和codeLong
是未定义的。不要在函数的开头定义
link
,而是先执行逻辑来计算codeShort
和codeLong
,然后才定义link
。