0

I'm detecting extensions then taking actions based on the extension. So my question is why doesn't this work, seems logical enough eh?

var ext = url.split('.').pop().toLowerCase();
if (ext == 'avi' || 'mpg' || 'mpeg' || 'mp4' || '3gp') {
  This is a video (this always returns true...?)
} else if (ext == 'jpg' || 'jpeg' || 'gif' || 'png' || 'bmp') {
  This is a picture
} else {
  This extension isn't supported here
}

But this does? Unnecessary overhead?

var ext = url.split('.').pop().toLowerCase();
if (ext == 'avi' || ext == 'mpg' || ext == 'mpeg' || ext == 'mp4') {
  This is a video
} else if (ext == 'jpg' || ext == 'jpeg' || ext == 'gif' || ext == 'png') {
  This is a picture
} else {
  This extension isn't supported here
}

Is there a syntax issue I'm missing to make this work like example 1 without hitting the variable over and over? Concerned because this list is a lot larger than what is pictured in regards to the amount of extensions and seems like a lot of unnecessary code when it's all said and done.

4

3 回答 3

3

ext == 'avi' || 'mpg' || 'mpeg' || 'mp4' || '3gp'当您比较 ext 是否为真avi或任何一个'mpg' || 'mpeg' || 'mp4' || '3gp'为真时,该行将始终为

==操作员仅比较单个变量以供将来参考。

另一种可以用 a 进行比较的switch方法如下:

switch(ext) {//switch with fall throughs
    case 'avi':
    case 'mpg':
    case 'mpeg':
    case 'mp4':
        //we got a video
        break;
    case 'jpg':
    case 'jpeg':
    case 'gif':
    case 'png':
        //its a picture
        break;
    default:
        //this extension isn't suupported
}
于 2013-11-03T00:48:08.910 回答
1

“所以我的问题是为什么这不起作用”

因为这不是||操作员所做的。

我能想到的实现您的概念的最短语法是对每个条件使用正则表达式测试:

if (/^(avi|mpg|mpeg|mp4|3gp)$/.test(ext)) {

或者你可以使用一个数组:

if (['avi', 'mpg', 'mpeg', 'mp4', '3gp'].indexOf(ext) != -1) {

(假设您不担心 IE<=8,或者正在使用shim,或者使用 jQuery$.inArray()代替.indexOf().)

或者这似乎是一个使用switch语句的明显地方:

var ext = url.split('.').pop().toLowerCase();
switch(ext) {
    case 'avi':
    case 'mpg':
    case 'mpeg':
    case 'mp4':
    case '3gp':
       //  This is a video (this always returns true...?)
       break;
    case 'jpg':
    case 'jpeg':
    case 'gif':
    case 'png':
    case 'bmp':
       // This is a picture
       break;
    default:
       //  This extension isn't supported here
       break;
}
于 2013-11-03T00:49:48.467 回答
1

你的第一个if条件永远是真实的。

如果您有很多值要检查,那么我会建议类似

var video = ['avi', 'mpg'];
var audio = ['mpg', 'mpeg'];
if($.inArray(ext, video)){
    //video
} if($.inArray(ext, audio)){
    //audio
} else {
}
于 2013-11-03T00:50:49.910 回答