有人可以解释代码发生了什么吗?

时间:2016-06-19 10:03:35

标签: javascript function switch-statement

我想猜猜用户键入​​的字母类型。

var userLetter = prompt("Enter a letter and I will tell you what type of letter is","Enter here, wish me luck!");

function selectUserLetter(letter) {
    var returnType = "NA";

    if (userLetter.charCodeAt(0) >= "A".charCodeAt(0) && userLetter.charCodeAt(0) <= "Z".charcodeAt(0)) {
        returnType = "U";
    }
    else if (userLetter.charCodeAt(0) >= "a".charCodeAt(0) && userLetter.charCodeAt(0) <= "z".charcodeAt(0)) {
        returnType = "L";
    }
    else if (userLetter.charCodeAt(0) >= "0".charCodeAt(0) && userLetter.charCodeAt(0) <= "9".charcodeAt(0)) {
        returnType = "N";
    }

    return returnType;
}

switch (selectUserLetter(userLetter)) {
    case "U": 
        document.write("Your letter is Uppercase");
        break;

    case "L":
        document.write("Your letter is Lowercase");
        break;

    case "N":
        document.write("Your letter is a number");
        break;

    default:
        document.write("You typed anything else");
}

1 个答案:

答案 0 :(得分:3)

在您的代码中,片段"Z".charcodeAt"z".charcodeAt(0)"9".charcodeAt(0)charcodeAt函数调用组成。问题是JavaScript是一个案例性的langauge。因此,charcodeAt不存在,而是charCodeAt