2013-03-27 54 views

回答

8

假設您想知道在特定情況下使用findsome,它們的性能特徵可能相同。他們都以同樣的方式懶惰。

不同之處在於輸出。 find將返回該值,some將返回boolean


我檢查了源代碼(1.4.4)。 somefind內部都使用some(=== any)。因此,即使使用some的本地實施,它也會使findsome受益。

+0

另一個微妙的區別是,'some'將使用本地實現如果有的話,我不知道的情況也是如此'find' – 2013-03-27 17:56:04

2

如果你看看它的來源,你會發現這兩個是相同的,_.find實際上調用_.some。

_.find = _.detect = function(obj, iterator, context) { 
    var result; 
    any(obj, function(value, index, list) { 
    if (iterator.call(context, value, index, list)) { 
     result = value; 
     return true; 
    } 
    }); 
    return result; 
}; 

var any = _.some = _.any = function(obj, iterator, context) { 
    iterator || (iterator = _.identity); 
    var result = false; 
    if (obj == null) return result; 
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); 
    each(obj, function(value, index, list) { 
    if (result || (result = iterator.call(context, value, index, list))) return breaker; 
    }); 
    return !!result; 
};