今天周末在家無聊學習一下lodash. lodash目前的中文資料很少。而且api好像還被牆了。下面說一下lodash的arrary相關的方法。
1. chunk 英 [tʃʌŋk] 顧名思義,是對數組進行分塊的方法
- n. 大塊;矮胖的人或物
用法: _.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 去除假值
- adj. 緊湊的,緊密的;簡潔的
- vt. 使簡潔;使緊密結合
api: Creates an array with all falsey values removed. The values false
, null
, 0
, ""
, 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])
// []
如果更進一步探究:
_.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
props
(Array): The property names.[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]
以上就是lodash v3.8的所有數組方法,對比ECMAScript 5中的數組方法。確實在一些特殊操作上簡化了我們的一些特殊處理。