具有多个允许条件的Javascript if语句 [英] Javascript if statement with multiple permissible conditions

查看:96
本文介绍了具有多个允许条件的Javascript if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript:将一个值与多个值进行比较的最漂亮的方法

Javascript If用于检查文件扩展名无效的语句

在JS中,我试图检查扩展是否以pngjpg或gif结尾。我知道这可以通过switch语句来完成,但是我想知道是否有一种更简单的方法可以在 if 条件下将其全部抛出。喜欢:

In JS I'm trying to check whether an extension ends in "png" "jpg" or "gif". I'm aware this can be done with a switch statement, but I'm wondering if there's a simpler way to throw it all in the if conditional. Like:

    if (aExtensions[i].toLowerCase() == ('jpg' || 'png' || 'gif')) {}

达到此目的的最佳方式是什么?

What's the best way to achieve this?

推荐答案

你可以使用这样的数组:

You could use an array like this:

var extensions = ["jpg", "png", "gif"];

if (extensions.indexOf(aExtensions[i].toLowerCase()) > -1) {
    // match
}

在这种情况下,您存储有效扩展名。然后,您可以使用 Array indexOf 方法来查找数组中的任何项是否与特定扩展名匹配您正在查看 - 检查 0 或更高的值。

In this case, you store the "valid" extensions. Then, you can use the indexOf method of Array to find if any of the items in the array match the specific extension you're looking at - checking for a value that is 0 or greater.

旧版浏览器不支持indexOf ,因此您需要包含 polyfill 备份它。有几种解决方案。

indexOf isn't supported on older browsers, so you'd need to include a polyfill to back it up. There are several solutions for that.

当然,如果你只想使用 if 语句,你可以使用格式:

Of course, if you wanted to only use if statements, you could use this format:

var ext = aExtensions[i].toLowerCase();
if (ext == "jpg" || ext == "png" || ext == "gif") {
    // match
}

我能想到的另一种可能性是开关语句,如:

Another possibility I can think of is a switch statement, like:

var ext = aExtensions[i].toLowerCase();

switch (ext) {
    case "jpg":
    case "png":
    case "gif":
        // match
        break;
    case default:
        // No match
}

I也许包括它(其他答案首先,肯定),但我能想到的另一个是使用正则表达式,如:

I might as well include it (other answers had it first, definitely), but one more I can think of is using a regex, like:

if (/jpg|png|gif/i.test(aExtensions[i])) {
    // match
}

但请注意,您将永远无法单独获得延期,这就是为什么我更喜欢我给出的前两个选项之一。

But note that you will never be able to individually get the extensions back, and that's why I would prefer one of the first two options I gave.

这篇关于具有多个允许条件的Javascript if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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