Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

Javascript if statement with multiple permissible conditions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use an array like this:

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

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

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 isn't supported on older browsers, so you'd need to include a polyfill to back it up. There are several solutions for that.

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...