2014-02-15 75 views
1

我有一个HTML表单与文件上传选项,我在客户端(为了只允许某些文件扩展名)的文件格式快速验证。替代IF语句与多个OR

以下代码片段对我来说工作正常,但我想知道是否有更好或更快的方式来实现相同的,特别是。如果将来有更多的扩展被允许的话。

注意:这只是关于用多个OR语句检查文件扩展名的部分。

到目前为止我的代码(工作):

if(((fileNameShort.length <= 100) && (fileNameShort.indexOf('#') == -1)) && ((fileFormat == 'bmp') || (fileFormat == 'doc') || (fileFormat == 'docx') || (fileFormat == 'gif') || (fileFormat == 'jpeg') || (fileFormat == 'jpg') || (fileFormat == 'msg') || (fileFormat == 'png') || (fileFormat == 'pdf'))) 

有这方面的建议,蒂姆非常感谢。

回答

5

使用.indexOf()

,还可以使用.toLowerCase()如检查小写的文件格式

var arr=['bmp','doc','docx','gif','jpg','msg']; //create array filetypes 

if(fileNameShort.length <= 100 && fileNameShort.indexOf('#') === -1 && arr.indexOf(fileFormat.toLowerCase()) !== -1) 
+1

这是完美的 - 非常感谢您的快速回复。一旦可用,我会接受。 – user2571510

+0

@ user2571510欢迎高兴它:) –

3

您正在使用方式也可能括号。

if ( 
    ( 
    (fileNameShort.length <= 100) 
    && (fileNameShort.indexOf('#') == -1) 
) 
    && 
    ( 
    (fileFormat == 'bmp') || (fileFormat == 'doc') || (fileFormat == 'docx') || (fileFormat == 'gif') || (fileFormat == 'jpeg') || (fileFormat == 'jpg') || (fileFormat == 'msg') || (fileFormat == 'png') || (fileFormat == 'pdf') 
) 
) 

相当于

if ( 
    fileNameShort.length <= 100 
    && fileNameShort.indexOf('#') == -1 
    && ( 
    fileFormat == 'bmp' || fileFormat == 'doc' || fileFormat == 'docx' || fileFormat == 'gif' || fileFormat == 'jpeg' || fileFormat == 'jpg' || fileFormat == 'msg' || fileFormat == 'png' || fileFormat == 'pdf' 
) 
) 

相当于

if ( 
    fileNameShort.length <= 100 
    && fileNameShort.indexOf('#') == -1 
    && /^(bmp|docx?|gif|jpe?g|msg|png|pdf)$/i.test(fileFormat) 
) 
+0

谢谢,这也是非常有用的! – user2571510