是否有更简单的方法来获得多个条件?使用JS有多个if else条件的简写?
if(suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif'){
console.log('not an image.');
}
是否有更简单的方法来获得多个条件?使用JS有多个if else条件的简写?
if(suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif'){
console.log('not an image.');
}
使用一个阵列可以被看作是一个速记,虽然它确实增加(可忽略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.');
}
而不是与indexOf的数组,您可以使用ojb ECT与在或hasOwnProperty:
if (suffix in {jpg:'', jpeg:'', png:'', gif:''})
或
if ({jpg:'', jpeg:'', png:'', gif:''}.hasOwnProperty(suffix))
一个对象的方法效果很好,如果你可以使用其他东西的对象。
也许不是短,但所有的case语句的恋人:
switch(suffix){
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
break;
default:
console.log('not an image.');
break;
}
我喜欢上面的一个,但什么是'in'相反,因为我觉得你得到了它向后;)? 'out'不起作用。 – Squirrl
没有'out',你必须否定这个条件:'if(!suffix in ...)' – Greg
@Greg我试过'if(!suffix in {jpg:'',jpeg:'',png:' ',gif:''}){...'但没有骰子。 – Squirrl