_.filter(collection, [predicate=_.identity])
遍历 collection(集合)元素,返回 predicate(断言函数)返回真值 的所有元素的数组。 predicate(断言函数)调用三个参数:(value, index|key, collection),返回一个新的过滤后的数组。
例子:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
源码解析:
function filter(array, predicate) {
let index = -1
let resIndex = 0
const length = array == null ? 0 : array.length
const result = []
// 如果旧数组的值满足断言函数的条件,就把值添加到新数组中
while (++index < length) {
const value = array[index]
if (predicate(value, index, array)) {
result[resIndex++] = value
}
}
return result
}
网友评论