为什么我的 if-else 语句不能使用 OR ( | | ) 来工作?

当我运行该程序时,控制台给出一个错误,指出“星期日”(和“星期六”,基于用户输入)不存在。我在 if 语句中尝试了多种带括号的组合,但没有任何效果。


var day = prompt("Enter a day of the week.");

console.log("Day is: " + day);

//if user input is equal to Sunday OR user input is equal to Saturday,

if (getText(day) == "Sunday" || getText(day) == "Saturday") {

  console.log("It's the weekend!");

} else {

  console.log("Can't wait for the weekend to get here.");

}


长风秋雁
浏览 68回答 2
2回答

慕婉清6462132

您应该删除它getText,它将正常工作:var day = prompt('Enter a day of the week.');console.log('Day is: ' + day);if (day == 'Sunday' || day == 'Saturday') {  console.log("It's the weekend!");} else {  console.log("Can't wait for the weekend to get here.");}

30秒到达战场

如果用户单击“确定”或单击“取消”,该prompt()函数始终返回 a 。在您的情况下,只要您输入一些内容并单击“确定”,就会出现一个字符串,可能是或。stringnullday"Sunday""Saturday"但是,如果您希望将大写字母和小写字母视为相同,例如"sunday"相当于"Sunday",则应使用toLowerCase()ortoUpperCase()方法来确保两个字符串要么全部小写,要么全部大写。像下面这样:var day = prompt("Enter a day of the week.");console.log("Day is: " + day);//if user input is equal to Sunday OR user input is equal to Saturday,if (day.toLowerCase() == "sunday" || day.toLowerCase() == "saturday") {  console.log("It's the weekend!");} else {  console.log("Can't wait for the weekend to get here.");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript