简体   繁体   中英

Shorter way to write multiple “or”-conditions in if-statement

I just started learning JavaScript a few days ago and I am wondering:

var input = prompt();

var checkVowel = function (input) {
    if (input === "a" || input === "e" || input === "i" || input === "o" || input === "u") {
        return true;
    } else {
        return false;
    }
}

checkVowel(input);

Isn't there a shorter way to write the multiple inputs instead of input === "e" each time?

You can do this with regex:

var checkVowel = function(input) {
  return /^[aeiou]$/.test(input);
};

Or using indexOf with an array:

var checkVowel = function(input) {
  return ['a','e','i','o','u'].indexOf(input) > -1;
};

You can also use a plain string:

var checkVowel = function(input) {
    return "aeiou".indexOf(input) >= 0;
};

I generally use this pattern for such a scenario:

var checkVowel = function(input) {
  if (['a', 'e', 'i', 'o', 'u'].indexOf(input) !== -1) {
      return true;
  } else {
    return false;
  }    
}

Isn't there a shorter way to write the multiple inputs instead of input === "e" each time?

If you want to check multiple inputs, there's no shorter way to do it other than to check every input (but there are better methods to do it, if you check all the other answers).

I'll advice you to read about the switch statement :

var checkVowel = function(input){

    switch (input) {
      case "a":
      case "e":
      case "i":
      case "o":
      case "u":
          return true;

      default:
          return false;
    }
}

The switch allows you to check multiple inputs in a readable way. This approach isn't shorter at all but is way more readable.

This is the shortest I got. You can also use Array.prototype.includes() to reduce multiple OR conditions.

const isVowel = input => ['a', 'e', 'i', 'o', 'u'].includes(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM