为什么字符串'Yes'的匹配是大小写敏感的?如何实现不区分大小写判断?
直接将用户输入的内容统一转换为全小写/全大写格式,再和相同大小写的目标字符串比较,即可实现不区分大小写的判断。
修改后的代码如下:
let cheer = prompt('Did the Team win?'); // toLowerCase()会把所有字符转为小写,转后和小写的'yes'比较即可 if(cheer.toLowerCase() != 'yes') { alert("We will win the next one!"); } else{ alert("Lets Go Team"); }
你也可以选择转为大写后对比,使用toUpperCase()方法,判断条件写为cheer.toUpperCase() != 'YES',效果完全一致。
如果需要兼容用户点击prompt取消按钮的场景(此时cheer值为null,直接调用字符串方法会报错),可以把判断条件调整为(cheer || '').toLowerCase() != 'yes'即可。
内容的提问来源于stack exchange,提问作者M Appel
相关产品推荐
相关产品推荐

