简体   繁体   中英

Using JS is there a shorthand for multiple if else conditions?

Is there a shorter way to have multiple if else conditions?

if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif'){

    console.log('not an image.');

}

Using an array can be seen as a shorthand, though it does add (negligible IMHO) overhead:

if (['jpg', 'jpeg', 'png', 'gif'].indexOf(suffix) === -1) {
  console.log('not an image.');
}

Edit: even shorter with RegExp :

if (!/jpe?g|png|gif/.test(suffix)) {
  console.log('not an image.');
}

Rather than an Array with indexOf , you can use an ojbect with in or hasOwnProperty :

if (suffix in {jpg:'', jpeg:'', png:'', gif:''})

or

if ({jpg:'', jpeg:'', png:'', gif:''}.hasOwnProperty(suffix))

An object approach works well if you can make use of the object for other things.

Maybe not shorter but for all case statement lovers:

switch(suffix){
   case 'jpg':
   case 'jpeg':
   case 'png':
   case 'gif':
       break;
   default:
       console.log('not an image.');
       break;
}

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