我正在尝试写一些检查字母不等于元音的东西.我知道我可以用正则表达式做到这一点,但为了更多地了解条件语句,我怎样才能更有效地编写这样的东西呢?
if (myArray[i] !== "a" || myArray[i] !=="e" || myArray[i] !=="i" || myArray[i] !=="o" || myArray[i] !=="u") {
console.log(myArray[i] + "");
}
Run Code Online (Sandbox Code Playgroud)
通过更有效率,我的意思是更多的干,而myArray[i] !== "a"不是重复这么多.
一个很好的方法是将所有元音都放在一个字符串中并使用indexOf:
if ("aeiou".indexOf(myArray[i]) === -1) {
// Do a thing if myArray[i] is not a vowel
}
Run Code Online (Sandbox Code Playgroud)
如果您需要不区分大小写,请使用myArray[i].toLowerCase().
正如Mike'Pomax'Kamermans在对此答案的评论中所提到的,使用正则表达式来检查整个字符串中的元音而不是检查每个单独的字符会更好更快.该解决方案看起来像:
if (!myString.match(/[aeiou]/) {
// Do a thing if myString doesn't have any vowels
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |