【JavaScript】Lodash在React Native中的使用

  Lodash是一个一致性、模块化、高性能的 JavaScript 实用工具库。

  Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单。Lodash 的模块化方法 非常适用于:

  • 遍历 array、object 和 string
  • 对值进行操作和检测
  • 创建符合功能的函数
import lodash from 'lodash';

 1、Array方法

  1.1 _.findIndex 

  返回值(number): 返回找到元素的 索引值(index),否则返回 -1

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

  1.2、_.findLastIndex

  返回值(number): 返回找到元素的 索引值(index),否则返回 -1

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

  1.3、_.indexOf

  返回值(number): 返回 值value在数组中的索引位置, 没有找到为返回-1

_.indexOf([1, 2, 1, 2], 2);
// => 1
 
// Search from the `fromIndex`.
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3

  1.4、_.reverse

  返回(Array): 返回 array.

  反转array,使得第一个元素变为最后一个元素,第二个元素变为倒数第二个元素,依次类推。

var array = [1, 2, 3];
 
_.reverse(array);
// => [3, 2, 1]
 
console.log(array);
// => [3, 2, 1]

  1.5、_.slice

  裁剪数组array,从 start 位置开始到end结束,但不包括 end 本身的位置。

  参数

  1. array (Array): 要裁剪数组。
  2. [start=0] (number): 开始位置。
  3. [end=array.length] (number): 结束位置。

  返回

  (Array): 返回 数组array 裁剪部分的新数组。

posted @ 2020-03-12 21:17  Mr·Xu  阅读(1315)  评论(1编辑  收藏  举报