gpt4 book ai didi

Javascript switch 语句比较让我陷入困境

转载 作者:行者123 更新时间:2023-12-03 01:27:19 24 4
gpt4 key购买 nike

我正在尝试使用 switch 语句将一些缩短的标记转换为完整的单词,上次我这样做,它有效,这次没那么有效。我认为类型有问题,但我不知道如何修复它。奇怪的是,修改器部分可以正常工作,但源部分却不能。

function keyToSource(key)
{
let fullSource, source, modifier;
if(key.includes("-"))
{
modifier = key.substring(key.indexOf("-") + 1, key.length);
source = key.substring(0, key.indexOf("-"));
}
else source = key;

switch(source)
{
case "Bo": fullSource = "Body"; break;
case "Ca": fullSource = "Capture"; break;
case "FA": fullSource = "Forearms"; break;
case "HL": fullSource = "Hindlegs"; break;
case "HS": fullSource = "Hard Shell"; break;
case "IR": fullSource = "Investigation Reward"; break;
case "PB": fullSource = "Palico Bonus"; break;
case "Pl": fullSource = "Plunderblade"; break;
case "SD": fullSource = "Shiny Drop"; break;
case "Ta": fullSource = "Tail"; break;
case "Tr": fullSource = "Track"; break;
default: fullSource = "Error"; break;
}

if(typeof modifier !== 'undefined')
{
switch(modifier)
{
case "C": fullSource += " carve"; break;
case "G": fullSource += "(Gold)"; break;
case "S": fullSource += "(Silver)"; break;
case "W": fullSource += " wound"; break;
default: fullSource = "Error" + fullSource; break;
}
}
return fullSource;
}


console.log(keyToSource("Ta"));
console.log(keyToSource("Ta-C"));

最佳答案

您的代码似乎可以工作。但是,您可以通过将 switch 语句移至对象中来清理逻辑:

function keyToSource(key) {
const k = key.split("-");

const source = {
"Bo": "Body",
"Ca": "Capture",
"FA": "Forearms",
"HL": "Hindlegs",
"HS": "Hard Shell",
"IR": "Investigation Reward",
"PB": "Palico Bonus",
"Pl": "Plunderblade",
"SD": "Shiny Drop",
"Ta": "Tail",
"Tr": "Track"
};

const modifier = {
"C": " carve",
"G": "(Gold)",
"S": "(Silver)",
"W": " wound"
};

return (source[k[0]] || "") + (modifier[k[1]] || "");
}

console.log(keyToSource("Ta"));
console.log(keyToSource("Ta-C"));
console.log(keyToSource("PB"));
console.log(keyToSource("Ta-G"));
console.log(keyToSource("SD-W"));
console.log(keyToSource("HS-C"));
console.log(keyToSource("as- da-sdf")); // test invalid entry

如果这不适合您,请随时发布说明。

关于Javascript switch 语句比较让我陷入困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51469849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com