如何使用||(OR)编写重复次数较少的if语句

How to write if statements with || (OR) with less repetition?

本文关键字:语句 if 何使用 OR      更新时间:2023-09-26

我正试图写一些东西来检查字母是否等于元音。我知道我可以用正则表达式做到这一点,但为了学习更多关于条件语句的知识,我如何才能更有效地编写这样的东西?

if (myArray[i] !== "a" || myArray[i] !=="e" || myArray[i] !=="i" || myArray[i] !=="o" || myArray[i] !=="u") {
    console.log(myArray[i] + "");
}

我所说的更有效率是指在不重复myArray[i] !== "a"的情况下更干燥。

一个很好的方法是将所有元音放在一个字符串中,并使用indexOf:

if ("aeiou".indexOf(myArray[i]) === -1) {
    // Do a thing if myArray[i] is not a vowel
}

如果需要区分大小写,请使用myArray[i].toLowerCase()


正如Mike‘Pomax’Kamermans在对这个答案的评论中所提到的,使用正则表达式检查整个字符串的元音比检查每个单独的字符更好、更快。这个解决方案看起来像:

if (!myString.match(/[aeiou]/) {
    // Do a thing if myString doesn't have any vowels
}

try,

//the myArray[i] is not a vowel
if (["e","e","o","i","u"].indexOf(myArray[i]) === -1 ) {
    console.log(myArray[i] + "");
}

您可以制作一个元音数组,然后搜索键是否在数组中。

var arrVowels = ['a','e','i','o','u'];
var myArray = ['b'];
if(!in_array(myArray[0], arrVowels)) {
    alert(" is not in the array! ");
}
function in_array(needle, haystack) {
  var key = '';
  for (key in haystack) {
    if (haystack[key] == needle) {
      return true;
    }
  }
  return false;
}

编辑

对于所有评论家,请参阅有关in_array()函数的更多信息:

http://phpjs.org/functions/in_array/