2014-01-17 25 views
1

此代碼來自recursion的部分。Javascript中的奇怪子句良好的部分

var getElementsByAttribute = function (att, value) { 
    var results = []; 

    walk_the_DOM(document.body, function (node) { 
     var actual = node.nodeType === 1 && node.getAttribute(att); 
     if (typeof actual === 'string' && 
       (actual === value || typeof value !== 'string')) { 
      results.push(node); 
     } 
    }); 

    return results; 
}; 

我不明白下面的子句點:

typeof actual === 'string' && (actual === value || typeof value !== 'string') 

它是如何從不同?

typeof actual === 'string' && actual === value 
+3

對於'value === 42',第一個條件是成立的哦 – Tibos

+0

Ohhhh,在看了5分鐘之後,我終於意識到兩個_different_變量的'string'性正在被測試'value'和'actual' 。 –

+0

@AlexWayne我應該盯着更長的時間... –

回答

2
typeof actual === 'string' && (actual === value || typeof value !== 'string') 

這將返回true當且僅當actual是一個字符串,並且或者actual === value,或value不是一個字符串。

typeof actual === 'string' && actual === value 

這將返回true當且僅當actual是一個字符串,要麼actual === value

換句話說,如果value不是字符串,第一個條件返回true,而第二個條件只會返回true,如果它是一個字符串,嚴格等於actual