find
_.find(list, predicate, [context])
Alias: detect
在 list 中逐项查找,返回第一个通过 predicate 迭代函数真值检测的元素值,如果没有元素通过检测则返回 undefined
。 如果找到匹配的元素,函数将立即返回,不会遍历整个 list。predicate 通过 iteratee 进行转换,以简化速记语法。
1 2
| var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); => 2
|
find.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import isArrayLike from './_isArrayLike.js';
import findIndex from './findIndex.js'; import findKey from './findKey.js';
export default function find(obj, predicate, context) { var keyFinder = isArrayLike(obj) ? findIndex : findKey; var key = keyFinder(obj, predicate, context); if (key !== void 0 && key !== -1) return obj[key]; }
|
findIndex.js
1 2 3 4
| import createPredicateIndexFinder from './_createPredicateIndexFinder.js';
export default createPredicateIndexFinder(1);
|
_createPredicateIndexFinder.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import cb from './_cb.js'; import getLength from './_getLength.js';
export default function createPredicateIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; }
|
findKey.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import cb from './_cb.js'; import keys from './keys.js';
export default function findKey(obj, predicate, context) { predicate = cb(predicate, context); var _keys = keys(obj), key; for (var i = 0, length = _keys.length; i < length; i++) { key = _keys[i]; if (predicate(obj[key], key, obj)) return key; } }
|