Lodash教程--(3)“集合”方法 (“Collection” Methods)

(1)_.countBy(collection, [iteratee= _.identity])

  • 创建一个组成对象,key(键)是经过 iteratee(迭代函数) 执行处理collection中每个元素后返回的结果,每个key(键)对应的值是 iteratee(迭代函数)返回该key(键)的次数(愚人码头注:迭代次数)。 iteratee 调用一个参数:(value)。
  • collection (Array|Object): 一个用来迭代的集合。
  • [iteratee=_.identity] (Array|Function|Object|string): 一个迭代函数,用来转换key(键)。
_.countBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': 1, '6': 2 }
 
// The `_.property` iteratee shorthand.
_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }

(2)_.every(collection, [predicate= _.identity])

  • 通过 predicate(断言函数) 检查 collection(集合)中的 所有 元素是否都返回真值。一旦 predicate(断言函数) 返回假值,迭代就马上停止。predicate(断言函数)调用三个参数: (value, index|key, collection)。
_.every([true, 1, null, 'yes'], Boolean);
// => false
 
var users = [
  {
    'user': 'barney', 'age': 36, 'active': false },
  {
    'user': 'fred',   'age': 40, 'active': false }
];
 
// The `_.matches` iteratee shorthand.
_.every(users, {
    'user': 'barney', 'active': false });
// => false
 
// The `_.matchesProperty` iteratee shorthand.
_.every(users, ['active', false]);
// => true
 
// The `_.property` iteratee shorthand.
_.every(users, 'active');
// => false

(3)_.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']

(4)_.find(collection, [predicate= _.identity], [fromIndex=0])

  • 遍历 collection(集合)元素,返回 predicate(断言函数)第一个返回真值的第一个元素。predicate(断言函数)调用3个参数: (value, index|key, collection)。
var users = [
  {
    'user': 'barney',  'age': 36, 'active': true },
  {
    'user': 'fred',    'age': 40, 'active': false },
  {
    'user': 'pebbles', 'age': 1,  'active': true }
];
 
_.find(users, function(o) {
    return o.age < 40; });
// => object for 'barney'
 
// The `_.matches` iteratee shorthand.
_.find(users, {
    'age': 1, 'active': true });
// => object for 'pebbles'
 
// The `_.matchesProperty` iteratee shorthand.
_.find(users, ['active', 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值