Javascript簡寫條件語句(推薦)

字號:


    下面小編就為大家?guī)硪黄狫avascript簡寫條件語句(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。
    經(jīng)常在各處牛人的代碼中看到許多簡寫的條件表達語句,看了一些介紹這方面的文章,覺得3 ways 2 say if這篇文章(http://www.thomasfrank.se/3_ways_2_say_if.html)還不錯。在這篇文章中作者對傳統(tǒng)的if...else...、?:、&&/||三種條件表達的寫法的特點及用處進行了總結(jié)歸納,簡述如下:
    1. if...else結(jié)構(gòu)
    // Set r to 0 or 1 
    var r= Math.floor(2*Math.random()) 
    // Set a, b and c to "small" if r==0 an else set them to "big" 
    // using three different techniques 
    // Method 1: If else 
    var a; if (r==0){a = "small"} else {a = "big"}; 
    // Method 2: Conditional operator 
    var b = r==0 ? "small" : "big"; 
    // Method 3: And/or operators 
    var c = r==0 && "small" || "big"; 
    // Check the values of our variables 
    alert(r+" "+a+" "+b+" "+c);
    2. if...else if...else結(jié)構(gòu)
    // Set r to 0,1,2 or 3 
    var r= Math.floor(4*Math.random()) 
    // Set a, b and c to "nada","small","big" and "huge" 
    // depending on the value or r using three different techniques 
    // Method 1: If.. else if... else 
    var a; 
    if (r==0){a="nada"} 
    else if (r==1){a="small"} 
    else if (r==2){a="big"} 
    else {a="huge"}; 
    // Method 2: Conditional operators 
    var b = 
    r==0 ? "nada"
    : r==1 ? "small"
    : r==2 ? "big"
    : "huge"; 
    // Method 3: And/or operators 
    var c = 
    r==0 && "nada"
    || r==1 && "small"
    || r==2 && "big"
    || "huge"; 
    // Check the values of our variables 
    alert(r+" "+a+" "+b+" "+c);
    3. 執(zhí)行函數(shù)
    // Set r to 0,1,2 or 3 
    var r= Math.floor(4*Math.random()) 
    // The global variable x and our four functions 
    var x=""; 
    nada=function(){x+="Nada! "}; 
    small=function(){x+="Small! "}; 
    big=function(){x+="Big! "}; 
    huge=function(){x+="Huge! "}; 
    // Call a specific function depending on the value of r 
    // using three different techniques 
    // Method 1: If.. else if... else 
    if (r==0){nada()} 
    else if (r==1){small()} 
    else if (r==2){big()} 
    else {huge()}; 
    // Method 2: Conditional operators 
    r==0 ? nada() 
    : r==1 ? small() 
    : r==2 ? big() 
    : huge(); 
    // Method 3: And/or operators 
    r==0 && (nada() || true) //nada()函數(shù)不一定返回true,為了保證后續(xù)的邏輯或||判斷不被執(zhí)行,需要返回true值,下同
    || r==1 && (small() || true) 
    || r==2 && (big() || true) 
    || huge(); 
    // Check the values of our variables 
    alert(r+" "+x);
    4. 執(zhí)行代碼
    // Set r to 0,1,2 or 3 
    var r= Math.floor(4*Math.random()) 
    // The global variable x 
    var x=""; 
    // Executing different code depending on the value of r 
    // using three different techniques 
    // Method 1: If.. else if... else 
    if (r==0){x+="Nada! "} 
    else if (r==1){x+="Small! "} 
    else if (r==2){x+="Big! "} 
    else {x+="Huge! "}; 
    // Method 2: Conditional operators 
    r==0 ? function(){x+="Nada! "}() 
    : r==1 ? function(){x+="Small! "}() 
    : r==2 ? function(){x+="Big! "}() 
    : function(){x+="Huge! "}(); 
    // Method 3: And/or operators 
    r==0 && (function(){x+="Nada! "}() || true) 
    //有人在評論中指出這里的匿名函數(shù)是不必需的,在只有一條可執(zhí)行代碼時是這樣的,但是如果有多條代碼需要執(zhí)行,匿名函數(shù)還是不錯的
    || r==1 && (function(){x+="Small! "}() || true) 
    || r==2 && (function(){x+="Big! "}() || true) 
    || function(){x+="Huge! "}(); 
    // Check the values of our variables 
    alert(r+" "+x);
    在這篇網(wǎng)文中,作者的關(guān)注重心是代碼的簡短與否,所以在一般情況下實現(xiàn)同等功能,作者更傾向于使用?:運算符,而覺得&&和||的方式要多打幾個字母,因而顯得比較累贅。在執(zhí)行函數(shù)的情況下,使用傳統(tǒng)的if...else更方便。在它的評論中有人提出,讓Client端代碼更簡潔短小作用大過提高一些不起眼的運行效率,這一點從某種程序上來說也是正確的。所以從形式上選取一種更簡潔的形式處理條件語句,可能比這些語句本身的運行效率更為重要,何況運行效率還會因UA而異。
    在只存在兩種條件的判斷中,用if...else或?:都是相當(dāng)直白,而&&和||的運算方式就稍嫌復(fù)雜。但是其實只要明白以下兩個基本原則,所有問題都會迎刃而解了:
    其一、當(dāng)用邏輯與&&和邏輯或||運算符運算時,方向都是自左向右的,&&運算到第一個值為false的條件(或可轉(zhuǎn)換為false的值,如null/undefined/0/""/NaN等)時停止,而運算到第一個值為true的條件(或可轉(zhuǎn)換為true的值)時停止;整個條件返回的值是最后檢測的條件的值,不一定只是true/false。
    其二、邏輯與&&運算符較邏輯或運算符相比,前者有更高的優(yōu)先級。
    根據(jù)第一個原則,r==0和"small"按自左向右的順序計算,如果r==0為true,則檢測"small","small"為非空字符串,故這樣c取值為"small";如果r==0為false,則直接開始邏輯或||的第二個條件"big"檢測,同樣的道理,c應(yīng)當(dāng)取值為"big"。根據(jù)第二個原則,在對上述代碼中的變量c的運算過程中,沒有必要加括號。
    由于使用?:和&&、||運算符在一定程序上能起到精簡代碼的作用,在jQuery這樣的庫源代碼中非常重要。歸納起來,這類運算符主要有兩方面的應(yīng)用,一是賦值或返回值,二是執(zhí)行代碼(暫且這樣分類)。
    用于賦值的用法在jQuery或其他庫中比比皆是,一個經(jīng)典應(yīng)用就是為接口實現(xiàn)默認(rèn)值的功能,我們可以很容易寫出這樣的代碼來,如:
    var myObj = function(options) {
      var color = options.color || this.defaults.defaults;
      var backgroundColor = options.backgroundColor
          || this.defaults.backgroundColor;
    };
    myObj.prototype.defaults = {
      color : "#393939",
      backgroundColor : "#222"
    }
    var myIns = new myObj({
      color : "#80FF80"
    });
    console.log("color:"+myIns.color+", backgroundColor: "+myIns.backgroundColor);
    不管用?:還是&&和||,由于不具備if...else與生俱來的代碼塊功能(用{}號包裹),所以它們都僅能執(zhí)行單行代碼,如:
    (xmlHttpRequest.readyState==4 && xmlHttpRequest.status ==200) ? alert("Success!"): alert("Failure!");
    所以如果有多條代碼需要執(zhí)行,就應(yīng)該用匿名函數(shù)。如:
    (xmlHttpRequest.readyState==4 && xmlHttpRequest.status ==200) ? function(){alert("Success!"); var a=100; alert(a);}: alert("Failure!");
    在jQuery 1.7.1源代碼這兩種簡寫形式太多了,如line 2643就有:
    // Hook for boolean attributes
    boolHook = {
      get: function( elem, name ) {
        // Align boolean attributes with corresponding properties
        // Fall back to attribute presence where some booleans are not supported
        var attrNode,
          property = jQuery.prop( elem, name );
        return property === true || 
    typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
          name.toLowerCase() :
          undefined;
      },
      set:function(){
    ...
      }
    }
    看來還得繼續(xù)學(xué)習(xí)進行總結(jié)。
    以上這篇Javascript簡寫條件語句(推薦)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考