Javascript簡寫條件陳述式

來源:互聯網
上載者:User

經常在各處牛人的代碼中看到許多簡寫的條件表達語句,看了一些介紹這方面的文章,覺得3 ways 2 say if這篇文章(http://www.thomasfrank.se/3_ways_2_say_if.html)還不錯。在這篇文章中作者對傳統的if...else...、?:、&&/||三種條件表達的寫法的特點及用處進行了總結歸納,簡述如下:

1. if...else結構

// 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結構

// 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. 執行函數

// 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()函數不一定返回true,為了保證後續的邏輯或||判斷不被執行,需要返回true值,下同
|| r==1 && (small() || true)
|| r==2 && (big() || true)
|| huge();

// Check the values of our variables
alert(r+" "+x);

4. 執行代碼

// 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)
//有人在評論中指出這裡的匿名函數是不必需的,在只有一條可執行代碼時是這樣的,但是如果有多條代碼需要執行,匿名函數還是不錯的
|| r==1 && (function(){x+="Small! "}() || true)
|| r==2 && (function(){x+="Big! "}() || true)
|| function(){x+="Huge! "}();

// Check the values of our variables
alert(r+" "+x);

在這篇網文中,作者的關注重心是代碼的簡短與否,所以在一般情況下實現同等功能,作者更傾向於使用?:運算子,而覺得&&和||的方式要多打幾個字母,因而顯得比較累贅。在執行函數的情況下,使用傳統的if...else更方便。在它的評論中有人提出,讓Client端代碼更簡潔短小作用大過提高一些不起眼的運行效率,這一點從某種程式上來說也是正確的。所以從形式上選取一種更簡潔的形式處理條件陳述式,可能比這些語句本身的運行效率更為重要,何況運行效率還會因UA而異。

在只存在兩種條件的判斷中,用if...else或?:都是相當直白,而&&和||的運算方式就稍嫌複雜。但是其實只要明白以下兩個基本原則,所有問題都會迎刃而解了:

其一、當用邏輯與&&和邏輯或||運算子運算時,方向都是自左向右的,&&運算到第一個值為false的條件(或可轉換為false的值,如null/undefined/0/""/NaN等)時停止,而運算到第一個值為true的條件(或可轉換為true的值)時停止;整個條件返回的值是最後檢測的條件的值,不一定只是true/false。

其二、邏輯與&&運算子較邏輯或運算子相比,前者有更高的優先順序。

根據第一個原則,r==0和"small"按自左向右的順序計算,如果r==0為true,則檢測"small","small"為非Null 字元串,故這樣c取值為"small";如果r==0為false,則直接開始邏輯或||的第二個條件"big"檢測,同樣的道理,c應當取值為"big"。根據第二個原則,在對上述代碼中的變數c的運算過程中,沒有必要加括弧。

由於使用?:和&&、||運算子在一定程式上能起到精簡代碼的作用,在jQuery這樣的庫原始碼中非常重要。歸納起來,這類運算子主要有兩方面的應用,一是賦值或傳回值,二是執行代碼(暫且這樣分類)。

用於賦值的用法在jQuery或其他庫中比比皆是,一個經典應用就是為介面實現預設值的功能,我們可以很容易寫出這樣的代碼來,如:

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與生俱來的代碼塊功能(用{}號包裹),所以它們都僅能執行單行代碼,如:

(xmlHttpRequest.readyState==4 && xmlHttpRequest.status ==200) ? alert("Success!"): alert("Failure!");

所以如果有多條代碼需要執行,就應該用匿名函數。如:

(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(){
  ...
}
}

看來還得繼續學習進行總結。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.