使用JS是否有多个条件的简写? [英] Using JS is there a shorthand for multiple if else conditions?

查看:45
本文介绍了使用JS是否有多个条件的简写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在更短的方法来拥有多个条件(如果有其他条件)?

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.');
}

使用 RegExp 甚至更短:

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

这篇关于使用JS是否有多个条件的简写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆