用于检查文件扩展名的 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.
}