一. lodash介紹
是什麼?
lodash是一個JavaScript語言的工具庫,內部封裝了很多字符串、數組、對象等常見數據類型的處理函數。
安裝
官方網站 (最權威最正確的就是查看官方網站)中分別詳細的介紹了 browser npm node.js 的安裝方法。
TypeScript中使用loadsh
不是必要但推薦安裝@types/lodash,該包包含類型定義,因此您的編譯器可以巧妙地提示您,您將能夠嚴格定義參數等類型。
note! @types/lodash包的版本需要和您項目中的typeScript 的版本對應兼容,否則編譯器可能會報類似下圖中的錯誤, 安裝時指定版本可避免一些出錯 npm安裝@types/lodash
![]()
二. lodash中提供的函數
note!:lodash的所有函數都不會在原有的數據上進行操作,而是複製出一個新的數據而不改變原有數據,返回的結果是新數據。
下面是對lodash中的部分函數進行舉例講解。
Array Methods
_.chunk(array, [size=1]) 對數組進行分塊
參數 array: 要分塊的數據 size: 分塊的大小[size選填 如果不填默認值為1]
const array = ['a', 'b', 'c', 'd'];
const chunk = _.chunk(['a', 'b', 'c', 'd'], 3);
console.log(array);
// => ['a', 'b', 'c', 'd']
console.log(chunk);
// => [['a', 'b', 'c'], ['d']]
_.uniq(array) 對array數組進行去重
_.uniq([2, 1, 2]);
// => [2, 1]
_.uniqBy(array, [iteratee=_.identity])
參數[iteratee=_.identity] (Function): 迭代器調用每個元素的執行的函數。
const uniqBy1 = _.uniqBy([2.1, 2.1, 2.3], _.identity);
// => [2.1, 2.3]
// 使用_.identity作為iteratee(即,直接比較對象,但對象引用不同,所以都會被視為不同)
const uniqBy2 = _.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], _.identity);
// => [{ x: 1 }, { x: 2 }, { x: 1 }]
// 下面兩種方法效果相同,只是寫法不同
const uniqBy3 = _.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x');
// => [{ x: 1 }, { x: 2 }]
const uniqBy4 = _.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], (object) => {
return object.x;
});
// => [{ x: 1 }, { x: 2 }]
Collection Methods
_.groupBy(collection, [iteratee=_.identity]) 對集合進行分組
_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { 4: [4.2], 6: [6.1, 6.3] }
const users = [
{name: 'zhangsan', age: 17},
{name: 'lisi', age: 16},
{name: 'wang', age: 18},
{name: 'liu', age: 17},
] as {name: string, age: number}[];
_.groupBy(users, 'age');
// => { 16: [{name: 'lisi', age: 16}], 17: [{name: 'zhangsan', age: 17}, {name: 'liu', age: 17}], 18: [{name: 'wang', age: 18}] }
Date Methods
_.now() 用於獲取當前時間的 Unix 時間戳
_.now();
// => 1728804822221
Function Methods
_.delay(func, wait, [args]) 等待一段時間後,在執行某個函數。
參數: func 控制執行時間的函數 wait 控制時間在多少毫秒後執行 args是func的參數。
_.delay((args) => { console.log('5 毫秒後的時間', _.now(), 'args:' + args); }, 5, 'this is args');
console.log(_.now());
// 1728805498795
// 5 毫秒後的時間 1728805498853 args:this is args
_.debounce(func, [wait=0], [options={}]) 創建一個防抖函數,只有在指定時間內的最後一次調用會生效。
Object Methods
const users = {
barney: { age: 36, active: true },
fred: { age: 40, active: false },
pebbles: { age: 1, active: true }
};
_.findKey(users, (o) => o.age < 40);
// => barney
// The `_.matches` iteratee shorthand.
_.findKey(users, { age: 1, active: true });
// => pebbles
.....更多未涉及到的方法請移步https://lodash.com/docs/4.17.15
最後
希望這篇文章能對您帶來幫助!瞭解lodash庫,若遇到操作數組,對象,集合,函數時,能夠想起lodash中已提供了方法,便於更快解決遇到的問題。