下包含函數編寫基於。降低()函數:試圖瞭解這個.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);
};
它在那裏返回'true',因爲第一個參數表示之前是否找到匹配。你看過Underscore文檔嗎? (或lodash,如果這就是你正在使用的。) – Robusto