2014-03-03 12 views

回答

6

使用一个阵列可以被看作是一个速记,虽然它确实增加(可忽略IMHO)开销:

if (['jpg', 'jpeg', 'png', 'gif'].indexOf(suffix) === -1) { 
    console.log('not an image.'); 
} 

编辑:即使正则表达式较短:

if (!/jpe?g|png|gif/.test(suffix)) { 
    console.log('not an image.'); 
} 
4

而不是与indexOf的数组,您可以使用ojb ECT与hasOwnProperty

if (suffix in {jpg:'', jpeg:'', png:'', gif:''}) 

if ({jpg:'', jpeg:'', png:'', gif:''}.hasOwnProperty(suffix)) 

一个对象的方法效果很好,如果你可以使用其他东西的对象。

+0

我喜欢上面的一个,但什么是'in'相反,因为我觉得你得到了它向后;)? 'out'不起作用。 – Squirrl

+0

没有'out',你必须否定这个条件:'if(!suffix in ...)' – Greg

+0

@Greg我试过'if(!suffix in {jpg:'',jpeg:'',png:' ',gif:''}){...'但没有骰子。 – Squirrl

2

也许不是短,但所有的case语句的恋人:

switch(suffix){ 
    case 'jpg': 
    case 'jpeg': 
    case 'png': 
    case 'gif': 
     break; 
    default: 
     console.log('not an image.'); 
     break; 
}