Javascript If用于检查文件扩展名的语句不起作用 [英] Javascript If statement used to check file extensions not working

查看:175
本文介绍了Javascript If用于检查文件扩展名的语句不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个人们可以输入文件路径的表单。我想确保他们输入的路径指向图片,所以这是我认为可行的。

I have a form in which people can enter file paths. I want to make sure that the paths they are entering point to pictures so here is what I thought would work.

function checkExt()
{
    var extension= /* I know that the code to cut the extension off of the file
                      is working correctly so for now let's just go with it ok */
    if(extension!="jpg" || "gif" || "bmp" || "png" || "whatever else")
        alert("The file extension you have entered is not supported");
}

但这不起作用。我已将其跟踪到if语句,因为如果我只选择一种文件来检查,那么它将正常工作。所以我的问题是你到底要改变什么才能让这个东西正常工作。我已经在这里待了大约三个小时了,这让我很生气。感谢您提前获得的所有帮助。

But this does not work. I have tracked it down to the if statement because if I select only 1 kind of file to check for, then it will work correctly. So my question to you is what the hell do I have to change to make this thing work correctly. I've been on this for about three hours now and it's driving me mad. Thanks for all of the help in advance.

推荐答案

这是一种语法和逻辑错误。它应该是:

That's a syntax and a logic error. It should be:

if (extension != "jpg" && 
    extension != "gif" && 
    extension != "bmp" && 
    extension != "png" && 
    extension != "whatever else") {
    // This will execute when the extension is NOT one of the expected 
    // extensions.
}

此外,您可以使用正则表达式更简洁地处理它:

Furthermore, you could handle it a little more succinctly with a regular expression:

if (!/jpg|gif|bmp|png|whatever/.test(extension)) {
    // This will execute when the extension is NOT one of the expected 
    // extensions.
}



附录:



extension 的值而不是支持的值之一时,上面的示例执行if语句的主体。如果要在 extensions 的值是支持的值之一时执行if语句的主体,则可以将逻辑从不等于/更改为等于/或者,像这样:

Addendum:

The examples above execute the body of the if-statement when the value of extension is not one of the supported values. If you wanted to execute the body of the if-statement when the value of extensions is one of the supported values, you would change the logic from not equal/and to equal/or, like so:

if (extension == "jpg" || 
    extension == "gif" || 
    extension == "bmp" || 
    extension == "png" || 
    extension == "whatever else") {
    // This will execute when the extension is one of the expected extensions.
}

同样,使用正则表达式会更简洁:

And again, it'd be more concise using a regular expression:

// I just removed the leading ! from the test case.
if (/jpg|gif|bmp|png|whatever/.test(extension)) {
    // This will execute when the extension is one of the expected extensions.
}

这篇关于Javascript If用于检查文件扩展名的语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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