Javascript If用于检查文件扩展名的语句不起作用
作者:互联网
我有一个表单,人们可以在其中输入文件路径.我想确保他们输入的路径指向图片,所以这是我认为可行的.
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语句,因为如果我只选择一种文件来检查,那么它将正常工作.所以我的问题是你到底要改变什么才能使这个东西正常工作.我已经在这里待了大约三个小时了,这让我很生气.感谢您提前获得的所有帮助.
解决方法:
这是一种语法和逻辑错误.它应该是:
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.
}
此外,您可以使用正则表达式更简洁地处理它:
if (!/jpg|gif|bmp|png|whatever/.test(extension)) {
// This will execute when the extension is NOT one of the expected
// extensions.
}
附录:
当extension的值不是受支持的值之一时,上面的示例将执行if语句的主体.如果你想在扩展的值是支持的值之一时执行if语句的主体,你可以将逻辑从不等于/和更改为等于/或,如下所示:
if (extension == "jpg" ||
extension == "gif" ||
extension == "bmp" ||
extension == "png" ||
extension == "whatever else") {
// This will execute when the extension is one of the expected extensions.
}
而且,使用正则表达式会更简洁:
// 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,operators,if-statement,file-extension 来源: https://codeday.me/bug/20190927/1824997.html