JS - Lodash工具库的使用详解4(Array数组函数1:查找指定元素、或索引)
四、Array 数组操作函数1:查找指定元素、或索引
1,随机获取一个元素
sample 方法可以从数组中获得一个随机元素。
1 | _.sample([1, 2, 3, 4]); // => 2 |
2,查找指定元素
(1)find 方法可以遍历数组元素,返回 predicate(断言函数)第一个返回真值的第一个元素。
1 2 3 4 5 6 7 8 9 10 | _.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 是从右至左遍历数组元素的。
1 2 3 4 | var result = _.findLast([1, 2, 3, 4], function (n) { return n % 2 == 1; }); console.log(result); |

3,查找指定元素的索引
(1)findIndex 方法类似 find,区别是该方法返回第一个通过 predicate 判断为真值的元素的索引值(index),而不是元素本身。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 中的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |