lodash学习笔记之Array方法

1. chunk   英 [tʃʌŋk]    顾名思义,是对数组进行分块的方法

    用法: _.chunk(array,number)  根据number对array进行均等的分块,如果array不能被number平分,则会留下一个余下的块。

_.chunk(['a','b','c','d'],-1);

//当 size<=1的时候,都是按1等分

> ['a','b','c','d']

//size=2

>[['a','b'],['c','d']]

//size=3

>[['a','b','c'],['d']]

//size>=4

>['a','b','c','d']

//不能这么传参数

_.chunk('a', 'b', 'c', 'd', 2)

>['a']


2. compact     去除假值

    api: Creates an array with all falsey values removed. The values falsenull0""undefined, and NaN are falsey.

    用法:_.compact(array)

//很明显第一个参数被处理了,剩下的参数都被忽视了。
_.compact('a','b','');

>["a"]

_.compact(['a','b','']);

>["a", "b"]

_.compact([0, 1, false, 2, '', 3,NaN,undefined]);

>[1, 2, 3]

3. difference  从数组中过滤元素

 用法:_.difference(array,[values])

   参数说明: array:要被检查/过滤的数组。

                  values:要被在array中剔除的值的集合

//注意两个参数都应该是数组类型
_.difference([1,2,4],2) [1, 2, 4] _.difference([1,2,4],[2]) [1, 4] _.difference([1,2,4],[-1]) [1, 2, 4]
_.difference([1,2,4],[1,2,4])
[]

4. drop  数组元素删除

     用法:类似于原生js方法中的slice   _.drop(array,number)

     从头开始删除number个数组元素。number不传的话默认按1处理

_.drop([1, 2, 3]);
// → [2, 3]

_.drop([1, 2, 3], 2);
// → [3]

_.drop([1, 2, 3], 5);
// → []

_.drop([1, 2, 3], 0);
// → [1, 2, 3]

5. dropRight    数组元素删除

    用法几乎和drop一样,不同的是从数组末尾开始删除。

6. dropRightWhile   数组元素过滤

    用法 _.dropRightWhile(array,[predicate=_.identity],[thisArg])

   -- Creates a slice of array excluding elements dropped from the end. 

   -- Elements are dropped until predicate returns false

   -- The predicate is bound to thisArg and invoked with three arguments: (value, index, array). 

    参数1:待处理的数组

    参数2:可以是(Function|Object|string),会对数组的每个元素调用 。

    参数3:判断是否删除的谓词。 

_.dropRightWhile([1, 2, 3], function(n) {
  return n > 1;
});
// → [1]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// → ['barney', 'fred']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.dropRightWhile(users, 'active', false), 'user');
// → ['barney']

// using the `_.property` callback shorthand  此处的解释应该是要drop不存在active属性的对象。
_.pluck(_.dropRightWhile(users, 'active'), 'user');
// → ['barney', 'fred', 'pebbles']

刚开始看的时候对第三条有点迷糊。怎么会一个都没有过滤掉呢?  查看了一下api.

 参数predicate实际上是有几种可能的值类型的,根据参数predicate的值类型的不同,会有如下几种不同的处理:

 1. function  此种情况下, 如果函数返回true,会把这一项drop掉。这种情况下函数一般只有两个参数:array和function

 2. string    如果参数predicate是一个属性名(string类型)的话,则返回值将会是此次遍历此属性的value。然后根据value进行drop。

  并且如果参数3 thisArg也有值的话,则会比较thisArg和predicate的返回值的不同。根据比较的值来进行drop。

  API:  If a property name is provided for predicate  the created _.property style callback returns the property value of the given element. 

  If a value is also provided for thisArg the created _.matchesProperty  style callback returns true for elements that have a matching property value, else false. 

 3. object  此种情况下。如果array中的某一项的属性和object中的属性一致,则返回true,否则就返回false. 

  API: If an object is provided for predicate  the created _.matches style callback returns true for elements that match the properties of the given object, else false

在测试的过程中,发现一个奇怪的例子:

var obj=[{'a':0,'b':'sa'},{'a':2,'b':'sadff'},{'a':3,'b':21}];  _.pluck(_.dropRightWhile(obj,'a',0),'a');
[0, 2, 3]

 

 7. dropWhile  数组元素过滤

    和dropRightWhile是基本一致的,不同点是从头到尾来进行计算的。

 

 8. fill  数组元素填充

     用法:  _.fill(array, value[start=0][end=array.length])

     从开始参数到结束参数,用value来替代或者填补数组元素。因为数组的下标是从0开始的,所以填充的范围是个左闭右开区间-填充的index范围包括start而不包括end.

     注意:此方法直接改变array,而不是返回一个数组。

复制代码
var array = [1, 2, 3];

_.fill(array, 'a');
console.log(array);
// → ['a', 'a', 'a']

_.fill(Array(3), 2);
// → [2, 2, 2]

_.fill([4, 6, 8], '*', 1, 2);
// → [4, '*', 8]
复制代码

 

9. findIndex  查询元素序号,遍历数组,如果查询到了符合要求的第一个元素则返回序号,如果没查询到符合要求的元素则返回-1.

    用法: _.findIndex(array[predicate=_.identity][thisArg])   _.identity()方法返回传给它的第一个参数。

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(chr) {
  return chr.user == 'barney';
});
// → 0

// using the `_.matches` callback shorthand
_.findIndex(users, { 'user': 'fred', 'active': false });
// → 1

// using the `_.matchesProperty` callback shorthand
_.findIndex(users, 'active', false);
// → 0

// using the `_.property` callback shorthand
_.findIndex(users, 'active');
// → 2

 

10. findLastIndex 类似于findIndex,只不过其返回的序列号是符合要求的最后一个。

      用法:_.findLastIndex(array[predicate=_.identity][thisArg])

 

11. first  返回数组第一个元素.

     用法:_.first(array)

     没什么好说的,如果数组为[]则返回undefined。

 

12. flatten 抹平嵌套数组

 用法:_.flatten(array[isDeep])

    isDeep为空或者false的情况下,只抹平第一层嵌套。为true的情况下,递归的进行抹平。

    

_.flatten([1, [2, 3, [4]]]);
// → [1, 2, 3, [4]]

// using `isDeep`
_.flatten([1, [2, 3, [4]]], true);
// → [1, 2, 3, 4]

 

13. flattenDeep 递归的抹平嵌套数组

用法:_.flattenDeep(array)

_.flattenDeep([1, [2, 3, [4]]]);
// → [1, 2, 3, 4]

 

14. indexOf

用法:_.indexOf(array, value[fromIndex=0])  从数组array中查询value的序号,参数3如果是true的话,执行二分查找。

_.indexOf([1, 2, 1, 2], 2);
// → 1

// using `fromIndex`
_.indexOf([1, 2, 1, 2], 2, 2);
// → 3

// performing a binary search
_.indexOf([1, 1, 2, 2], 2, true);
// → 2

 

15.initial  返回除了末尾元素的数组

用法:_.initial(array)

_.initial([1, 2, 3]);
// → [1, 2]

 

16. intersection 返回新数组,其值就是数组参数的交集

用法:_.intersection([arrays])

_.intersection([1, 2], [4, 2], [2, 1]);
// → [2]

17. last 返回参数数组的末尾元素

用法:_.last(array)

18. lastIndexOf  类似于indexOf,搜索方向为从末尾到开头

用法:_.lastIndexOf(array, value[fromIndex=array.length-1])

_.lastIndexOf([1, 2, 1, 2], 2);
// → 3

// using `fromIndex`
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// → 1

// performing a binary search
_.lastIndexOf([1, 1, 2, 2], 2, true);
// → 3

19.pull 移除值,直接在原数组上进行操作

用法:_.pull(array[values])

var array = [1, 2, 3, 1, 2, 3];

_.pull(array, 2, 3);
console.log(array);
// → [1, 1]

 

20. pullAt 按序号移除值,直接操作原数组并且返回移除的值组成的数组。

用法:_.pullAt(array[indexes])

var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);

console.log(array);
// → [5, 15]

console.log(evens);
// → [10, 20]

可以看出来,移除1,3位置的元素从逻辑上来说是同时移除的。避免了数组越界的问题。

21.remove 移除元素,对原数组进行操作,并且返回移除元素的集合。

用法:_.remove(array[predicate=_.identity][thisArg])

从参数可以看出来,参数的处理逻辑是类似于前面的dropRightWhile方法的。

API:Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). 

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});

console.log(array);
// → [1, 3]

console.log(evens);
// → [2, 4]

 

22. rest 移除数组首元素 和initial相反

用法:_.rest(array)

 

23.slice 数组截取

用法:_.slice(array[start=0][end=array.length])

那么和原生的slice有什么不同呢?

API:This method is used instead of Array#slice to support node lists in IE < 9 and to ensure dense arrays are returned.

 

24.sortedIndex 在对一个有序数组array进行插入的时候,返回value应该插入的位置。从左向右计算。

用法:_.sortedIndex(array, value[iteratee=_.identity][thisArg])

 API:Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order. If an iteratee function is provided it is invoked for value and each element of array to compute their sort ranking. The iteratee is bound to thisArg and invoked with one argument; (value). 

_.sortedIndex([30, 50], 40);
// → 1

_.sortedIndex([4, 4, 5, 5], 5);
// → 2

var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };

// using an iteratee function
_.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
  return this.data[word];
}, dict);
// → 1

// using the `_.property` callback shorthand
_.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
// → 1

 

25. sortedLastIndex 用法类似于sortedindex,不同的是从右至左计算插入的位置

用法:_.sortedLastIndex(array, value[iteratee=_.identity][thisArg])

_.sortedLastIndex([4, 4, 5, 5], 5);
// → 4

 

26. take 数组切片

用法:_.take(array[n=1])

API:Creates a slice of array with n elements taken from the beginning.

_.take([1, 2, 3]);
// → [1]

_.take([1, 2, 3], 2);
// → [1, 2]

_.take([1, 2, 3], 5);
// → [1, 2, 3]

_.take([1, 2, 3], 0);
// → []

 

27. takeRight 类似于take方法,执行方向不同。 

用法:_.takeRight(array[n=1])

_.takeRight([1, 2, 3]);
// → [3]

 

28. takeRightWhile  

用法:_.takeRightWhile(array[predicate=_.identity][thisArg])

API:Creates a slice of array with elements taken from the end. Elements are taken until predicate returns falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). 

_.takeRightWhile([1, 2, 3], function(n) {
  return n > 1;
});
// → [2, 3]

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// → ['pebbles']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.takeRightWhile(users, 'active', false), 'user');
// → ['fred', 'pebbles']

// using the `_.property` callback shorthand
_.pluck(_.takeRightWhile(users, 'active'), 'user');
// → []

 

29. takeWhile 类似于takeRightWhile 执行顺序相反

用法:_.takeWhile(array[predicate=_.identity][thisArg])

  

30.union 数组合并,去除重复值

用法:_.union([arrays])

_.union([1, 2], [4, 2], [2, 1]);
// → [1, 2, 4]

 

31.uniq/unique 数组去重 

用法:_.uniq(array[isSorted][iteratee][thisArg])

API:Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only the first occurence of each element is kept. Providing true for isSorted performs a faster search algorithm for sorted arrays. If an iteratee function is provided it is invoked for each element in the array to generate the criterion by which uniqueness is computed. The iteratee is bound to thisArg and invoked with three arguments: (value, index, array). 

_.uniq([2, 1, 2]);
// → [2, 1]

// using `isSorted`
_.uniq([1, 1, 2], true);
// → [1, 2]

// using an iteratee function
_.uniq([1, 2.5, 1.5, 2], function(n) {
  return this.floor(n);
}, Math);
// → [1, 2.5]

// using the `_.property` callback shorthand
_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// → [{ 'x': 1 }, { 'x': 2 }]

 

32. unzip  zip的逆运算,还原zip后的数组

用法:_.unzip(array)

var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
// → [['fred', 30, true], ['barney', 40, false]]

_.unzip(zipped);
// → [['fred', 'barney'], [30, 40], [true, false]]

var zipped2=_.zip(['fre','shike'],[30,40,50],[true,false]);
// →
[['fred', 30, true], ['barney', 40, false],[undefined,50,undefined]]

 

33. unzipWith  在数组重组的时候同时进行某些操作

用法:_.unzipWith(array[iteratee][thisArg])

[iteratee] (Function): The function to combine regrouped values.

var zipped = _.zip([1, 2], [10, 20], [100, 200]);
// → [[1, 10, 100], [2, 20, 200]]

_.unzipWith(zipped, _.add);
// → [3, 30, 300]

可以看出来,在unZip之后,因为iteratee是_.add函数,因此将unZip的结果进行了相加。

 

34. without  从数组中去除某些值

用法:_.without(array[values])

_.without([1, 2, 1, 3], 1, 2);
// → [3]

不同于difference方法。其values参数可以不是一个数组,而是接在array参数之后的零散参数。

 

35.xor  对称消除重复值

API:Creates an array that is the symmetric difference of the provided arrays.

symmetric:对称的,均匀的。

用法:_.xor([arrays])

_.xor([1, 2], [4, 2]);
// [1, 4]

  _.xor([1,2],[3,4])
  // [1, 2, 3, 4]
  _.xor([1,2],[3,4,1])
  // [2, 3, 4]
  _.xor([1,2],[1,2])
  // []

如果更进一步探究:

1
2
3
4
5
6
7
8
9
10
_.xor([1,2],[1,2],[1])
[1]
_.xor([1,2],[1,2],[3,4])
[3, 4]
_.xor([1,2],[1,2],[1,4])
[1, 4]
_.xor([1,2],[1,2],[1,4],[1,4])
[]
_.xor([1,2],[1,2],[3,4,1])
[3, 4, 1]

是不是很有趣? 推测如果前面的数组参数两两消除了,后面的数组即使有重复的元素,还是会保留。

.xor([1,2],[1,2],[1,2])
[1, 2]

所以说,xor这个函数应该是参数两个两个进行重复值消除的。

_.xor([1,2],[1,2,3],[1,2])

如果n和n+1还有未消除的非重复值,那么会和n+2和n+3消除后保留下来的数组进行合并。

 

36. zip  数组分组

API:Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

用法:_.zip([arrays])

_.zip(['fred', 'barney'], [30, 40], [true, false]);
// → [['fred', 30, true], ['barney', 40, false]]

如果zip的数组长度不一,则会这样

_.zip(['fred', 'barney'], [30, 40,50], [true, false]);
// → [['fred', 30, true], ['barney', 40, false],[undefined,50,undefined]]

 

37. zipObject  数组转对象   ._pair的反操作,

用法:_.zipObject(props[values=[]])

API:The inverse of _.pairs; this method returns an object composed from arrays of property names and values. Provide either a single two dimensional array, e.g. [[key1, value1][key2,value2]] or two arrays, one of property names and one of corresponding values.

Arguments

  1. props (Array): The property names.
  2. [values=[]] (Array): The property values.
_.zipObject([['fred', 30], ['barney', 40]]);
// → { 'fred': 30, 'barney': 40 }

_.zipObject(['fred', 'barney'], [30, 40]);
// → { 'fred': 30, 'barney': 40 }

可以看出来,当只有一个数组参数的时候,最底层的数组被解读为[key,value]

当有两个数组参数的时候,这两个数组分别被解释为name和key的集合。 然后被组装为object返回。

 

38.  zipWith  类似于unzipWith函数

用法:_.zipWith([arrays][iteratee][thisArg])

_.zipWith([1, 2], [10, 20], [100, 200], _.add);
// → [111, 222]

猜你喜欢

转载自blog.csdn.net/uncle_long/article/details/80364373
今日推荐