Javascript开关语句比较使我陷入循环

时间:2018-07-22 22:46:22

标签: javascript string types switch-statement

我正在尝试使用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"));

1 个答案:

答案 0 :(得分:1)

您的代码似乎有效。但是,您可以通过将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

如果这对您没有帮助,请随时发表澄清。