如果您確實想要採用Lodash方式,則可以使用_.partial
和_.result
或_.invoke
構建自定義謂詞的等效項。使用Array的some
功能和箭頭功能
var predicate = _.partial(_.invoke, _, 'hasChanges');
// later...
// a function which only checks, without creating a
// new anonymous function each time.
function check() {
return _.some(users, predicate);
}
ES6:
_.some(users, _.partial(_.invoke, _, 'hasChanges'));
謂詞可以一次創建,以後使用。
items.some(item => item.hasChanged());
_.some
(或最some
功能實現)打破在第一truthy發生循環。像_.invokeMap
這樣的函數將調用每個對象的函數,而不管結果哪個效率比我們已經擁有的自定義謂詞效率低。
,但它們不調用對象上的函數。
// The `_.matches` iteratee shorthand.
_.some(users, { 'user': 'barney', 'active': false });
// => false
// The `_.matchesProperty` iteratee shorthand.
_.some(users, ['active', false]);
// => true
// The `_.property` iteratee shorthand.
_.some(users, 'active');
// => true
下將無法正常工作:
_.invoke(_.identity, "hasChanges")
它類似於_.identity.hasChanges()
。
偉大的信息! ES6語法看起來確實是最簡潔的方法。 感謝您澄清爲什麼簡單的_.invoke不起作用,以及提醒我__identity和佔位符_是完全不同的! – user715374