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"; 

posted @ 2014-05-27 08:49  Ranran  阅读(5357)  评论(0编辑  收藏  举报