.toLowerCase 和 null 属性 出错

Error with .toLowerCase and null property

我想做的是让用户能够从提示中输入多个选项,但我做不到,所以无论输入“rcz”有无大写字母都无所谓,我总是得到同样的错误。 我需要我的计数器出现在控制台中,但我得到的是:

Uncaught TypeError: Cannot read properties of null (reading 'toLowerCase')

我使用的代码:

alert(`Choose one or more cars. If you want to stop press ESC`);
let userPrompt = prompt(`Available cars: 208, 308, RCZ`);
let promptToLC = userPrompt.toLowerCase();
let counter = 0;
while(userPrompt != null) {
    switch(promptToLC) {
        default:
            alert(`We don't have that car. Try again.`);
            break;
        case "208":
            counter = counter + 1;
            break;
        case "308":
            counter = counter + 1;
            break;
        case "rcz":
            counter = counter + 1;
            break;
    }
    userPrompt = prompt(`Available cars: 208, 308, RCZ`);
    promptToLC = userPrompt.toLowerCase();
}
console.log(counter);

这很可能是因为在用户没有输入的情况下取消提示的情况下,'userPrompt' 有可能为空。

您可以通过将语句更改为以下内容来断言提示不为空:

let promptToLC = (userPrompt ? userPrompt:"").toLowerCase();

此条件语句将确保在“userPrompt”为 null(默认为假值)的情况下,不会使用 null 值,而是使用空字符串。

prompt(`Available cars: 208, 308, RCZ`);

returns 一个字符串或 null。如果 userPromptnulluserPrompt.toLowerCase(); 会导致错误。您可以使用 conditional chaining operator ?.:

修复它

alert(`Choose one or more cars. If you want to stop press ESC`);
let userPrompt = prompt(`Available cars: 208, 308, RCZ`);
let promptToLC = userPrompt?.toLowerCase();
let counter = 0;
while(userPrompt != null) {
    switch(promptToLC) {
        default:
            alert(`We don't have that car. Try again.`);
            break;
        case "208":
            counter = counter + 1;
            break;
        case "308":
            counter = counter + 1;
            break;
        case "rcz":
            counter = counter + 1;
            break;
    }
    userPrompt = prompt(`Available cars: 208, 308, RCZ`);
    promptToLC = userPrompt?.toLowerCase();
}
console.log(counter);

或没有promptToLC的修改逻辑:

alert(`Choose one or more cars. If you want to stop press ESC`);
let userPrompt = prompt(`Available cars: 208, 308, RCZ`);
let counter = 0;
while(userPrompt != null) {
    // const promptToLC = userPrompt.toLowerCase();
    switch(userPrompt.toLowerCase()) {
        default:
            alert(`We don't have that car. Try again.`);
            break;
        case "208":
            counter = counter + 1;
            break;
        case "308":
            counter = counter + 1;
            break;
        case "rcz":
            counter = counter + 1;
            break;
    }
    userPrompt = prompt(`Available cars: 208, 308, RCZ`);
}
console.log(counter);