lodash是js的一個實用工具庫,現在es6盛行,搭配loash工具庫是最方便的一件事了。lodash內部封裝了關於字符串,數組,對象一些常見數據類型的處理函數。它所有函數都不會在原有的數據上進行操作,而是複製出一個新的數據而不改變原有數據。
使用傳統的js方法處理數據,我們難免會用到遍歷取數,而使用loash工具庫我們可以減少這一環節,所以還是安利一下。
下面整理的是項目上比較常用到的方法,主要是針對於數組。做一個屬於自己的方法查找工具書吧。
使用之前要引用:
import {} from 'loash';
1.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])
[]
通常,我用此方法不僅可以剔除不需要的屬性,也可以用於比較兩個數組是否相同。
2.drop()
說明:數組元素刪除
用法: _.drop(array,number),類似於原生js方法中的slice
參數說明:
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]
3.first()
說明:返回數組第一個元素.
用法:_.first(array)
如果數組爲[]則返回undefined。
4.findIndex()
說明:查詢元素序號,遍歷數組,如果查詢到了符合要求的第一個元素則返回序號,如果沒查詢到符合要求的元素則返回-1,類似於js中常用的indexof()方法
用法: .findIndex(array, [predicate=.identity], [thisArg])
參數說明:
array: 需要檢查/遍歷的數組
_.identity()方法返回傳給它的第一個參數。
thisArg 需要搜索的索引
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
5.findLastIndex()
說明:類似於js中的lastIndexOf(), 其返回的序列號是符合要求的最後一個。
用法:.findLastIndex(array, [predicate=.identity], [thisArg]),見findIndex()方法。
6.dropRight 數組元素刪除
用法幾乎和drop一樣,不同的是從數組末尾開始刪除。
7.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]
8.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
9.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
10.pull()
用法:_.pull(array, [values])
說明:移除值,直接在原數組上進行操作
var array = [1, 2, 3, 1, 2, 3];
_.pull(array, 2, 3);
console.log(array);
// → [1, 1]
11.last()
用法:_.last(array)
說明:返回參數數組的末尾元素
12.flattenDeep
用法:_.flattenDeep(array)
說明:遞歸的抹平嵌套數組
_.flattenDeep([1, [2, 3, [4]]]);
// → [1, 2, 3, 4]
13.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]
14.xor()
用法:_.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這個函數應該是參數兩個兩個進行重複值消除的。如果n和n+1還有未消除的非重複值,那麼會和n+2和n+3消除後保留下來的數組進行合併。
15.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位置的元素從邏輯上來說是同時移除的。避免了數組越界的問題。
16.remove()
用法:.remove(array, [predicate=.identity], [thisArg])
說明:移除元素,對原數組進行操作,並且返回移除元素的集合。
從參數可以看出來,參數的處理邏輯是類似於前面的dropRightWhile方法的。
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]
17.chunk 對數組進行分塊的方法
用法: _.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']
18.compact()
說明:去除假值,將空值,0, NaN去除掉。
用法:_.compact(array)
//很明顯第一個參數被處理了,剩下的參數都被忽視了。
_.compact('a','b','');
>["a"]
_.compact(['a','b','']);
>["a", "b"]
_.compact([0, 1, false, 2, '', 3,NaN,undefined]);
>[1, 2, 3]
19.dropRightWhile()
用法 .dropRightWhile(array,[predicate=.identity],[thisArg])
說明: 數組元素過濾
參數說明:
參數1:待處理的數組
參數2:可以是(Function|Object|string),會對數組的每個元素調用,會依賴於第三個參數【thisArg】 。
參數3:判斷是否刪除的謂詞。
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']
參數predicate實際上是有幾種可能的值類型的,根據參數predicate的值類型的不同,會有如下幾種不同的處理:
1.function 此種情況下, 如果函數返回true,會把這一項drop掉。
2. string 如果參數predicate是一個屬性名(string類型)的話,返回值將會是遍歷此屬性的value。然後根據value進行drop。並且如果參數3 thisArg也有值的話,則會比較thisArg和predicate的返回值的不同。根據比較的值來進行drop。
3. object 此種情況下。如果array中的某一項的屬性和object中的屬性一致,則返回true,否則就返回false.
20.initial()
說明:返回除了末尾元素的數組
用法:_.initial(array)
_.initial([1, 2, 3]);
// → [1, 2]
21.rest()
說明: 移除數組首元素 和initial相反
用法:_.rest(array)
22.intersection()
說明:返回新數組,其值就是數組參數的交集
用法:_.intersection([arrays])
_.intersection([1, 2], [4, 2], [2, 1]);
// → [2]
23.slice 數組截取
用法:_.slice(array, [start=0], [end=array.length])
24.union()
說明:數組合並,去除重複值
用法:_.union([arrays])
_.union([1, 2], [4, 2], [2, 1]);
// → [1, 2, 4]
25.uniq/unique
說明:數組去重
用法:_.uniq(array, [isSorted], [iteratee], [thisArg])
_.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 }]
26.keys()
說明:取出對象中所有的key值組成新的數組。
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.keys(new Foo);
// => ['a', 'b'] (iteration order is not guaranteed)
_.keys('hi');
// => ['0','1']
類似object.keys(),返回對象中可枚舉屬性的數組。
以上只是列舉了平時使用到比較多的方法,會不斷更新,當然個人覺得js的方法有些也挺不錯的,就不列舉在此了。