JS - Lodash工具库的使用详解4(Array数组函数1:查找指定元素、或索引)

作者: hgweb 发布时间: 2019-10-11 浏览: 2821 次 编辑

四、Array 数组操作函数1:查找指定元素、或索引

1,随机获取一个元素

sample 方法可以从数组中获得一个随机元素。

_.sample([1, 2, 3, 4]);   // => 2

2,查找指定元素

(1)find 方法可以遍历数组元素,返回 predicate(断言函数)第一个返回真值的第一个元素。

_.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', false]);   // => object for 'fred'
  
// The `_.property` iteratee shorthand.
_.find(users, 'active');   // => object for 'barney'

(2)findLast 方法类似 find,不同之处在于,findLast 是从右至左遍历数组元素的。

var result = _.findLast([1, 2, 3, 4], function(n) {
    return n % 2 == 1;
  });
console.log(result);

原文:JS - Lodash工具库的使用详解4(Array数组函数1:查找指定元素、或索引)

3,查找指定元素的索引

(1)findIndex 方法类似 find,区别是该方法返回第一个通过 predicate 判断为真值的元素的索引值(index),而不是元素本身。

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
  
_.findIndex(users, function(o) { return o.user == 'barney'; });   // => 0
  
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });   // => 1
  
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);   // => 0
  
// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');   // => 2

(2)findLastIndex 方法类似 findIndex, 区别是它是从右到左的迭代集合 array 中的元素。

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
  
_.findLastIndex(users, function(o) { return o.user == 'pebbles'; });   // => 2
  
// The `_.matches` iteratee shorthand.
_.findLastIndex(users, { 'user': 'barney', 'active': true });   // => 0
  
// The `_.matchesProperty` iteratee shorthand.
_.findLastIndex(users, ['active', false]);   // => 2
  
// The `_.property` iteratee shorthand.
_.findLastIndex(users, 'active');   // => 0

JS Lodash工具库的使用详解系列:

JS - Lodash工具库的使用详解1(使用debounce函数实现防抖)

JS - Lodash工具库的使用详解2(使用throttle函数实现节流)

JS - Lodash工具库的使用详解3(String字符串操作函数)

JS - Lodash工具库的使用详解4(Array数组函数1:查找指定元素、或索引)

JS - Lodash工具库的使用详解5(Array数组函数2:获取部分数组片段)

JS - Lodash工具库的使用详解6(Array数组函数3:移除、修改原数组内容)

JS - Lodash工具库的使用详解7(Array数组函数4:数组排序、打乱)

JS - Lodash工具库的使用详解8(Array数组函数5:数组与对象间的转换)

JS - Lodash工具库的使用详解9(Array数组函数6:如果不是数组强制转成数组)

JS - Lodash工具库的使用详解10(Array数组函数7:根据指定规则进行分组、统计)

JS - Lodash工具库的使用详解11(Array数组函数8:创建指定范围数字的数组)

JS - Lodash工具库的使用详解12(创建一个只能调用1次、n次的函数)

JS - Lodash工具库的使用详解13(创建一个对某函数结果取反的函数)

JS - Lodash工具库的使用详解14(浅拷贝,深拷贝)

JS - Lodash工具库的使用详解15(深比较,判断是否包含某属性或属性值)

JS - Lodash工具库的使用详解16(判断是否为空)

JS - Lodash工具库的使用详解17(类型检查)

JS - Lodash工具库的使用详解18(生成随机数)