有没有更好的方法来表达这个 if 语句有很多可能的条件?
Is there a better way to phrase this if statement from having many possible conditions?
我正在编写一个代码,我需要确定一个字母是辅音字母还是元音字母。我试图找到一种方法来简化我的 if 语句,但除了带有多个 || 可能语句的 if 语句之外,我不知道有什么方法。有没有办法做到这一点,它包含一个条件下的所有字母,例如:if(myStr === 'a', 'e', 'i', 'o', 'u') {}
?我还有其他尚未使用的变量,但这是我的代码:
class Word {
constructor(x, y, str) {
this.x = x;
this.y = y;
this.str = str;
}
I
//Find out the word's composition of consonants and vowels and divide word into sections
divSect(word) {
var newStr = this.str.split("");
for(var i = 0; i < newStr.length; i ++) {
if(newStr[i] === "a" || newStr[i] === "e" || newStr[i] === "i" || newStr[i] === "o" || newStr[i] === "u") {
console.log("test");
}
}
}
}
正则表达式可以工作。
if (/[aeiou]/.test(newStr[i])) {
console.log("test");
}
您可以使用 String.includes
:
console.log('aeiou'.includes('a'))
console.log('aeiou'.includes('b'))
在您的代码中,您可以将 if
语句写成
if ('aeiou'.includes(newStr[i])) {
// ...
}
我正在编写一个代码,我需要确定一个字母是辅音字母还是元音字母。我试图找到一种方法来简化我的 if 语句,但除了带有多个 || 可能语句的 if 语句之外,我不知道有什么方法。有没有办法做到这一点,它包含一个条件下的所有字母,例如:if(myStr === 'a', 'e', 'i', 'o', 'u') {}
?我还有其他尚未使用的变量,但这是我的代码:
class Word {
constructor(x, y, str) {
this.x = x;
this.y = y;
this.str = str;
}
I
//Find out the word's composition of consonants and vowels and divide word into sections
divSect(word) {
var newStr = this.str.split("");
for(var i = 0; i < newStr.length; i ++) {
if(newStr[i] === "a" || newStr[i] === "e" || newStr[i] === "i" || newStr[i] === "o" || newStr[i] === "u") {
console.log("test");
}
}
}
}
正则表达式可以工作。
if (/[aeiou]/.test(newStr[i])) {
console.log("test");
}
您可以使用 String.includes
:
console.log('aeiou'.includes('a'))
console.log('aeiou'.includes('b'))
在您的代码中,您可以将 if
语句写成
if ('aeiou'.includes(newStr[i])) {
// ...
}