本文初衷是想列舉一些比較「多餘」的API以及對應原生JS寫法;後面發現API過多,精力有限,慢慢的變成記錄那些有助於提升開發效率的API,但願對您有所幫助。對於那些,根據名字或者描述便能知道其實際用途的API,筆者未作Demo演示。各位看官能夠查看對應官方文檔便能快速應用於實際開發,Lodash中文API上有詳細介紹。javascript
Lodash 是一個一致性、模塊化、高性能的 JavaScript 實用工具庫。採用函數類API,多數API都不修改傳入的參數;html
Lodash功能強大,涵蓋了前端開發中能遇到的大部分邏輯功能點,使用Lodash能大大提升咱們的開發效率。但這也有一個弊端:便利每每會使咱們變"懶"。仁者見仁智者見智,Lodash帶來便利同時,咱們應該時刻記住:JavaScript纔是咱們的根本;前端
Lodash中「多餘」的API並很少餘,API內部處理了不少開發者經常忽略的異常狀況,使代碼更加安全;java
對於大部分Lodash API對比手寫JS對應邏輯功能點,並不會提升性能;git
Lodash,gitHub star數爲45K。同時是一個學習教材,經過閱讀源碼能幫助咱們夯實JavaScript基礎。函數式API讓每一個邏輯功能點代碼量不大,比較容易理解。基礎差的同窗能夠經過閱讀源碼,手寫源碼的方式來夯實JavaScript,好比手寫:柯里化,防抖,節流,bind,字符串template等。github
lodash.compact([0, 1, false, 2, '', 3]) [0, 1, false, 2, '', 3].filter(_ => _) // [1, 2, 3] 複製代碼
lodash.concat([1], [2, 3, 4], [5, 6]) [1, ...[2, 3, 4], ...[5, 6]] // [1, 2, 3, 4, 5, 6] 複製代碼
lodash.fill([1,2,3],'a') [1,2,3].fill('a')) // ['a', 'a', 'a'] lodash.fill(Array(3),'b') Array(3).fill('b') // ['b', 'b', 'b'] 複製代碼
const first1 = lodash.head([1, 2, 3]) const [first2] = [1, 2, 3] // 1 複製代碼
lodash.flatten([1, [2, [3, [4]], 5]])) [1, [2, [3, [4]], 5]].flat(1)) // [1, 2, [3, [4]], 5] 複製代碼
lodash.flattenDeep([1, [2, [3, [4]], 5]]) lodash.flattenDepth([1, [2, [3, [4]], 5]], 3) [1, [2, [3, [4]], 5]].flat(Infinity) // [1, 2, 3, 4, 5] 複製代碼
lodash.fromPairs([['fred', 30], ['barney', 40]]) Object.fromEntries([['fred', 30], ['barney', 40]]) // {fred: 30, barney: 40} 複製代碼
lodash.pull([1, 2, 3, 1, 2, 3], 2, 3) [1, 2, 3, 1, 2, 3].filter(item => ![2, 3].includes(item)) // [1, 1] 複製代碼
lodash.difference([3, 2, 1], [4, 2]) [3, 2, 1].filter(item => ![4, 2].includes(item)) 複製代碼
var other = lodash.tail([1, 2, 3]) var [, ...other] = [1, 2, 3] // 可擴展不包含前第n個元素 複製代碼
let arr1 = [1, 2, 3, 4, 5] arr1 = lodash.take(arr1, 2) // 作賦值,刪除元素 const arr2 = [1, 2, 3, 4, 5] arr2.length = 2 // 修改長度,直接刪除後面元素,可用於清空數組 // [1, 2] 複製代碼
pullAt (根據下標選擇元素,分到兩個數組)後端
takeRight ( 返回從結尾元素開始n個元素的數組切片 )數組
// 倒數解構 const [beforeLast, last] = lodash.takeRight([1, 2, 3, 4], 2) console.log(beforeLast, last) // 3 4 複製代碼
lodash.zipObject(['a', 'b'], [1, 2]); // => { 'a': 1, 'b': 2 } 複製代碼
lodash.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } 複製代碼
remove(元素篩選,分到兩個數組)安全
sortedUniq (去重,排序)markdown
takeRightWhile ( 從array
數組的最後一個元素開始提取元素,直到 predicate
返回假值 )
uniqBy (去重,排序)
Collection不少API都能讓人眼前一亮,在實際開發中都能獲得應用。
// 遍歷數組有點多餘 lodash([1, 2]).forEach((val) => { console.log(val) }) // 遍歷對象就 lodash({ a: 1, b: 2 }).forEach((val, key) => { console.log(val, key) }) // 原生js寫法 **** 注意數組解構順序 Object.entries({ a: 1, b: 2 }).forEach(([key, val]) => { console.log(val, key) }) 複製代碼
console.log(lodash([true, 1, null, 'yes']).every(Boolean)) // false // 等效於 console.log([true, 1, null, 'yes'].every(Boolean)) // false const users = [ { user: 'barney', age: 40, active: false }, { user: 'fred', age: 40, active: false }, ] // *******眼前一亮的用法******** console.log(lodash(users).every({ active: false, age: 40 })) // true // 等效於 console.log(users.every((item) => item.active === false && item.age === 40)) // true console.log(lodash.find(users, { user: 'fred' }) === users[1]) // true console.log(lodash.filter(users, { user: 'fred' })) // object for ['fred'] console.log(lodash.some(users, { user: 'fred' })) // true 複製代碼
const users = [ { id: 'a', age: 40, height: 1 }, { id: 'b', age: 39, height: 2 }, { id: 'c', age: 38, height: 2 }, { id: 'd', age: 40, height: 2 }, ] console.log(lodash.groupBy(users, 'age')) // 按age分組:{38:obj for ['a'], 39:obj for ['b'], 40:obj for ['c', 'd']} console.log(lodash.groupBy(users, ({ age, height }) => age + height)) // 按age+height結果分組:{40:obj for ['c'], 41:obj for ['a', 'b'], 42:obj for ['d']} 複製代碼
invokeMap (分解item:循環調用方法,方法返回值替換集合item)
keyBy ( 生成對象:組成聚合的對象 ;key值來源於回調,回調參數爲對應集合item;value爲item)
orderBy | sortBy(排序:可指定多個排序字段,有優先級;可控制升序和反序)
partition (站隊:根據回調返回值,返回 [ 返回值爲true的item數組 , 返回值爲false的item數組])
reject (找茬:找出不符合條件的item集合,相似!filter)
sample (抽籤:集合中隨機取一個)
sampleSize (抽籤:集合隨機抽取n個)
shuffle (打亂)
下面列舉的是實際開發中應用場景較多的API,具體的用法就不作demo了,具體可參看官網API。
func
,直到當前堆棧清理完畢 Lang下多爲判斷類型的API,常規的isXxx判斷類型API就不作過多的介紹。下面介紹一些好用的API。
maxBy(最大值) | minBy(最小值)| meanBy (求平局值)| sumBy (求和)
const users = [ { id: 'b', age: 39, height: 2 }, { id: 'a', age: 40, height: 1 }, { id: 'c', age: 38, height: 2 }, { id: 'd', age: 40, height: 2 }, ] console.log(lodash.maxBy(users, 'age')) // obj for 'a' console.log(lodash.maxBy(users, ({ age, height }) => age + height)) // obj for 'd' 複製代碼
/** * 判斷數字是否在某個區間 * @param string 範圍 * demo: * const ten = 10 * ten.isInRange('[1,10]') // true * ten.isInRange('[1,10)') // false */ Number.prototype.isInRange = function (range = '[1,10]') { // 1. 應該對range進行正則校驗 const val = this.valueOf() const isStartEqual = range.startsWith('[') const isEndEqual = range.endsWith(']') let [start, end] = range .slice(1, range.length - 1) // 去頭尾符號 '1,10' .split(',') // 切割字符串 ['1', '10'] .map(Number) // 轉換數字 [1, 10] start > end && ([start, end] = [end, start]) // 保證start < end const isGt = isStartEqual ? val >= start : val > start // >start const isLt = isEndEqual ? val <= end : val < end // <end return isGt && isLt } const ten = 10 console.log(ten.isInRange('[1,10]')) // true console.log(ten.isInRange('[1,10)')) // false 複製代碼
下面只記錄讓人眼前一亮的API
const object = { a: [{ b: { c: 3 } }, 4] } console.log(lodash.at(object, ['a[0].b.c', 'a[1]'])) // [3, 4] console.log(lodash.at(object, 'a[0].b.c')) // [3] console.log(lodash.get(object, 'a[0].b.c')) // 3 複製代碼
const defaultData = { a: { b: 1, c: 3 } } // 默認值 const settingData = { a: { b: 2 } } // 設置的值 // 當對象只有一層的時候對象結構還挺好用,相似於lodash.defaults // 當對象層級不止一層的時候,層級深的默認值就被沖刷掉了 const mergeData = { ...defaultData, // 默認值放在前面 ...settingData, } console.log(mergeData) // {a:{b:2}} // 會改變settingData,因此取副本 const mergeDataGood = JSON.parse(JSON.stringify(settingData)) lodash.defaultsDeep(mergeDataGood, defaultData) // 默認值在最後 console.log(mergeDataGood) // {a:{b: 2, c: 3}} 複製代碼
const dValue = a&&a.b&&a.b.c&&a.b.c.d
。ES2020
已定稿增長了操做符:?.
來解決上述問題。上面等價寫法爲:const dValue = a?.b?.c?.d
const obj = { a: { b: { c: { d: 'dValue' } } } } const obj2 = {} console.log(lodash.has(obj,'a.b.c.d')) // true console.log(lodash.has(obj2,'a.b.c.d')) // false 複製代碼
invert : key-value反轉,返回新對象,新對象爲舊對象的value-key;
invertBy :相似invert,能對新對象的key進行處理;
mapKeys :處理對象的key,生成新對象;
mapValues :處理對象value,生成新對象;
merge | mergeWith :對象合併
var object = { a: [{ b: 2 }, { d: 4 }], obj: { key1: 'value1', key2: 'value2' }, } var other = { a: [{ c: 3 }, { e: 5 }], obj: { key1: 'valueOther1', key3: 'valueOther2' }, } console.log(lodash.merge(object, other)) /** { a: [ { b: 2, c: 3 }, { d: 4, e: 5 }, ], obj: { key1: 'valueOther1', key2: 'value2', key3: 'valueOther2' }, } */ 複製代碼
const model = { key1: 'value1', // 須要發送到後端的數據 key2: 'value2', key3: 'value3', pageKey1: 'pageValue1', // 頁面用到的字段 pageKey2: 'pageValue2', pageKey3: 'pageValue3', } // 1. 原始寫法 const postData1 = { key1: model.key1, key2: model.key2, key3: model.key3, } // omit const postData2 = lodash.omit(model, ['pageKey1', 'pageKey2', 'pageKey3']) // omitBy // 剔除key包含page字段 const postData3 = lodash.omitBy(model, (value, key) => key.includes('page')) console.log(lodash.isEqual(postData1, postData2)) // true console.log(lodash.isEqual(postData1, postData3)) // true 複製代碼
pick | pickBy:摘選對象屬性,功能和omit | omitBy 相反。當要剔除的屬性比保留屬性多的時候採用pick
set:字符串key鏈路設置值,和get對應
API過多,下面只記錄Seq讓人眼前一亮的API
var users = [ { user: 'barney', age: 36 }, { user: 'fred', age: 40 }, { user: 'pebbles', age: 1 }, ] const first = lodash .chain(users) .sortBy('age') .map(function (o) { return o.user + ' is ' + o.age }) .head() .value() // 注意這裏要運行.value()才運行,獲得結果 console.log(first) // pebbles is 1 複製代碼
lodash的String API多爲轉換不一樣值的API,如:首字母大寫、駝峯式、html屬性式、下劃線鏈接式、全小寫、首字母小寫、編碼、填充,去空格等API。
惟一亮眼的API:template(字符串模板)。可應用於 動態國際化、拼接國際化較優實現
const compiled = lodash.template('hello <%= user.name %>!') console.log(compiled({ user: { name: 'fred' } })) // hello fred! 複製代碼