2015-12-08 66 views
2

下包含函數編寫基於。降低()函數:試圖瞭解這個.contain的語法()函數

_.reduce = function(collection, iterator, accumulator) { 
    each(collection,function(value){ 
    accumulator=iterator(accumulator,value); 

    }); 
    return accumulator 
    }; 

林被語法有點困惑在這裏,或者是它在邏輯上寫的?爲什麼我們先使用if語句並在設置item === target之前先返回'wasFound'?如果item === target爲true,那麼我們將wasFound設置爲true?

 _.contains = function(collection, target) { 
     return _.reduce(collection, function(wasFound, item) { 
      if (wasFound) { 
      return true; 
      } 
      return item === target; 
     }, false); 
     }; 
+0

它在那裏返回'true',因爲第一個參數表示之前是否找到匹配。你看過Underscore文檔嗎? (或lodash,如果這就是你正在使用的。) – Robusto

回答

1

第一次reduce功能使匹配(return item === target)將隨後返回true對於要遍歷所有剩餘項目。沒有理由檢查未來的值是否與目標匹配,因爲我們只關心集合是否至少包含一次目標。這就是爲什麼如果wasFound是真的,它只是返回true。

0

你使用這樣的:

_.contains([1,2,3], 2); 
//=> true 

_.contains([1,2,3], 5); 
//=> false 

它需要一個列表和一個元素。它設置wasFoundfalse最初和然後在collection檢查每個item:(1)如果wasFoundtrue,然後一些以前item一直相同target,所以設置wasFoundtrue保持它;(2)否則,將wasFound設置爲item === target的值。

+0

OP正試圖理解'_.contains',因爲它使用'_.reduce'的匹配實現。使用本地'reduce'功能違背了他們試圖理解的內容。 –

+0

@MikeC謝謝。我意識到這是錯誤的做法。糾正。 –