jQuery中的&& ||


jQuery1.2.6 clean方法中有這么一段第一眼看去會讓人暈掉的方法。完全不知其所言。 
“||, && 可以這樣用?”,“這段東西最終返回的是個什么對象啊?” 
// Trim whitespace, otherwise indexOf won't work as expected 
var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div"); 

var wrap = 
// option or optgroup 
!tags.indexOf("<opt") && 
[ 1, "<select multiple='multiple'>", "</select>" ] || 

!tags.indexOf("<leg") && 
[ 1, "<fieldset>", "</fieldset>" ] || 

tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && 
[ 1, "<table>", "</table>" ] || 

!tags.indexOf("<tr") && 
[ 2, "<table><tbody>", "</tbody></table>" ] || 

// <thead> matched above 
(!tags.indexOf("<td") || !tags.indexOf("<th")) && 
[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] || 

!tags.indexOf("<col") && 
[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] || 

// IE can't serialize <link> and <script> tags normally 
jQuery.browser.msie && 
[ 1, "div<div>", "</div>" ] || 

[ 0, "", "" ]; 

   深入研究查詢資料后才明白,這一段到低是想搞些干什么,也才被這巨牛的寫法所折服。 

                
// Logical AND && : the second operand will always be returned, no matter whatever it is, except the first operand is one of (0, -0, null, "", false, undefined, NaN) for such condition, the first operand will be returned.    
                
// Logical OR || : the first operand will always be returned, except the first operand is one of (0, -0, null, "", false, undefined, NaN). 
// in this situation the second operand will be returned, no matter what the second operand it is, even it's the same to the first one. 


//<<Professional JavaScript for Web Developers 2nd Edition.pdf>> Page 52. 

   因為已經trim過了,前后都沒有了空格,主要是前面沒空字符串,所以此時判斷是否以什么開頭也就是startWith,最簡單就是寫成tags.indexOf("<opt"), 看法indexOf,返回值當startWith為true時,剛好返回的是0, 其它情況:  1,找到但是在字符串中間出現的返回值是大於0正數;2,完全沒出現過時,返回為-1. 反正一樣都是非0的數,而妙處就在在JavaScript定義中對number類對象,只是為0時,才被認為可轉化為false,其它包括負數都被認為為true. 

The indexOf() method returns the position of the first occurrence of a specified value in a string. 

If the Boolean object has no initial value, or if the passed value is one of the following: 

0, -0, null, "", false, undefined, NaN 
the object it is set to false. For any other value it is set to true (even with the string "false")! 

This method returns -1 if the value to search for never occurs. 

  那么假設如果tag是以"<opt"開頭的話,那indexOf的值就是0,而前面加一個!號后, !tag.indoexOf("<opt") 的值就為true了, 那么就相當於是 
true && [...], 再回頭看看 && 的定義, 前一個值為false時才返回前一個參數值, 否則總是返回第二個參數(即便它自己也是false 或 NaN什么的)。 

   總之呢, jQuery原碼中中這兩個邏輯符號用的頻率是相當相當的高,特別是 || 。 
jQuery中幾乎沒那幾方法實現中不用它的。 用好它們的確可以使代碼更簡化,優雅,高效。 

例如下段,其常被用於,有默認值的情況。a不行,讓b上,b也不行時,那就只能c了。退而求其次的處理方式。 
// Start an animation from one number to another 
custom: function(from, to, unit){ 
this.startTime = now(); 
this.start = from; 
this.end = to; 
this.unit = unit || this.unit || "px"; 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM