【问题标题】:Switch Case vs. Conditional?切换案例与条件?
【发布时间】:2012-09-07 15:52:11
【问题描述】:

我发现了这篇文章:Switch case with three parameters?,我正在考虑使用 switch case 传递多个参数,如下所示:

switch (array($var1, $var2, $var3)) {
case array(true, false, false):
    echo "hello";
    break;
}

似乎存在一些问题,这是否是最有效的方法。情绪似乎是 if 条件更合适。但是,当我看到我正在写的条件时,我不确定?例如,这感觉很混乱(请注意,我已经删除了大约 6 个其他条件,以免让您感到厌烦):

if ( 
  csz == "google" || 
  csz == "bing" || 
  csz == "yahoo" || 
  csz == "dogpile" || 
  csz == "millionshort" && 
  cs == '' ) { 
    $("li.phone").replaceWith('<li class="phone">' + phoneNaturalSearch + '</li>');
}
else if ( 
  csz == "facebook" && 
  cs == '' ) { 
    $("li.phone").replaceWith('<li class="phone">' + phoneFacebook + '</li>');
}
else if ( 
  csz == "google-plus" || 
  csz == "plus" ) { 
    $("li.phone").replaceWith('<li class="phone">' + phoneGooglePlus + '</li>');
}
// Snipped out other conditionals
else { 
    $("li.phone").replaceWith('<li class="phone">' + phoneDefault + '</li>');
}

在这里使用多个参数切换会更有效,还是会遇到性能影响?我想我应该写代码,看看它是否真的不那么混乱,但我想我会先把它从大师那里退回来。

【问题讨论】:

  • build a jsPerf test case 并找出自己。这可能取决于运行它的浏览器。
  • 我从来没有使用过这个工具。谢谢你指点我!
  • 我不明白这是如何工作的?你不能只比较两个数组jsfiddle.net/acXV4/1
  • 解释起来有点复杂,但你是对的,数组可能更合适。基本上,我有从 URL(可能存在也可能不存在)中提取的参数,以及从 Google Analytics cookie 中提取的参数。更重要的参数是通过 URL 传递的参数,因为这意味着传入链接很可能来自付费广告。不太重要的是来自 GA utmz cookie 的参数。我正在测试查看哪些存在,哪些不存在,并向用户提供要拨打的适当电话号码。

标签: jquery conditional switch-statement


【解决方案1】:

我觉得如果你有这么多条件,我更喜欢使用 switch 语句,这会使你的代码更清晰,更容易理解。 对于属于此特定类别的条件,您可以省略休息...

var phoneType= '';

switch(csz){ 
  case "google" : 
  case  "bing" : 
  case "yahoo" :
  case "dogpile"  : 
  case "millionshort" : 
    if (cs==''){ 
        phoneType = phoneNaturalSearch ;
        break;
    }
    else {
        goto case "facebook";
    }
  case "facebook" :
    if (cs==''){ 
        phoneType = phoneFacebook  ;
        break;
    }
    else {
        goto case "google-plus";
    }
  case "google-plus" :
  case "plus"  : 
    phoneType = phoneGooglePlus ;
    break;
  default : 
    phoneType = phoneDefault  ;
    break;
}

$("li.phone").replaceWith('<li class="phone">' + phoneType + '</li>');

【讨论】:

  • 我喜欢它的外观!它更干净,更符合我的想法。我要试一试 - 谢谢!
【解决方案2】:

谈到更简洁的解决方案,另一种方法是将它们保存在二维数组中并检索元素索引。

看看这个:

var csz= 'amazon';

var groups = [['google','yahoo','bing'],['facebook','orkut','hi5','zurker'],['amazon','bestbuy','sears']];
var groupIndex = getIndexOf(groups,csz);
if(groupIndex ==1){
    //code here
    alert("1");
}else if(groupIndex ==2){
    //code here
    alert("2");
}else if(groupIndex ==3){
    //code here
    alert("3");
}

function getIndexOf(myArray,element){
    for(var i=0;i<groups.length;i++){
        for(var j=0;j<groups[i].length;j++){
            if(myArray[i][j]==element){
                return i;  
            }
        }
    }        
    return -1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2017-07-21
    • 2015-05-12
    相关资源
    最近更新 更多