作者:JS強迫症患者
鏈接:https://juejin.im/post/5ed3cd366fb9a047f129c39a
本文初衷是想列舉一些比較“多餘”的API以及對應原生JS寫法;後面發現API過多,精力有限,慢慢的變成記錄那些有助於提高開發效率的API,希望對您有所幫助。對於那些,根據名字或者描述便能知道其實際用途的API,筆者未做Demo演示。各位看官可以查看對應官方文檔便能快速應用於實際開發,Lodash中文API 上有詳細介紹。
一、收穫
lodash那些功能強大的API
lodash那些“多餘”的API及原生JS對應寫法
二、 Lodash
Lodash 是一個一致性、模塊化、高性能的 JavaScript 實用工具庫。採用函數類API,多數API都不修改傳入的參數;
Lodash功能強大,涵蓋了前端開發中能遇到的大部分邏輯功能點,使用Lodash能大大提高我們的開發效率。但這也有一個弊端:便利往往會使我們變"懶"。仁者見仁智者見智,Lodash帶來便利同時,我們應該時刻記住:JavaScript纔是我們的根本;
Lodash中“多餘”的API並不多餘,API內部處理了很多開發者常常忽略的異常情況,使代碼更加安全;
對於大部分Lodash API對比手寫JS對應邏輯功能點,並不會提高性能;
Lodash,gitHub star數爲45K。同時是一個學習教材,通過閱讀源碼能幫助我們夯實JavaScript基礎。函數式API讓每個邏輯功能點代碼量不大,比較容易理解。基礎差的同學可以通過閱讀源碼,手寫源碼的方式來夯實JavaScript,比如手寫:柯里化,防抖,節流,bind,字符串template等。
三、數組 Array
“多餘”指數:☆☆
compact(過濾假值)
lodash.compact([0, 1, false, 2, '', 3])
[0, 1, false, 2, '', 3].filter(_ => _)
// [1, 2, 3]
concat(數組拼接)
lodash.concat([1], [2, 3, 4], [5, 6])
[1, ...[2, 3, 4], ...[5, 6]]
// [1, 2, 3, 4, 5, 6]
fill(填充)
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']
head(獲取第一個元素)
const first1 = lodash.head([1, 2, 3])
const [first2] = [1, 2, 3]
// 1
flatten(降1個維度)
lodash.flatten([1, [2, [3, [4]], 5]]))
[1, [2, [3, [4]], 5]].flat(1))
// [1, 2, [3, [4]], 5]
flattenDeep | flattenDepth(降爲一維數組)
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]
fromPairs(entries類型數組轉換爲對象)
lodash.fromPairs([['fred', 30], ['barney', 40]])
Object.fromEntries([['fred', 30], ['barney', 40]])
// {fred: 30, barney: 40}
pull(移除指定元素)
lodash.pull([1, 2, 3, 1, 2, 3], 2, 3)
[1, 2, 3, 1, 2, 3].filter(item => ![2, 3].includes(item))
// [1, 1]
Array自帶的reverse (數組翻轉)、slice(切割)、join(字符串拼接)、indexOf | lastIndexOf(匹配索引)等
“多餘”指數:☆
difference
lodash.difference([3, 2, 1], [4, 2])
[3, 2, 1].filter(item => ![4, 2].includes(item))
tail(返回不包含第一個元素的數組)
var other = lodash.tail([1, 2, 3])
var [, ...other] = [1, 2, 3] // 可擴展不包含前第n個元素
take (0 - 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]
眼前一亮的API
pullAt (根據下標選擇元素,分到兩個數組)
takeRight ( 返回從結尾元素開始n個元素的數組切片 )
// 倒數解構
const [beforeLast, last] = lodash.takeRight([1, 2, 3, 4], 2)
console.log(beforeLast, last) // 3 4
zipObject
lodash.zipObject(['a', 'b'], [1, 2]);
// => { 'a': 1, 'b': 2 }
zipObjectDeep
lodash.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
xor( 創建一個給定數組唯一值的數組 )
眼前二亮的API
remove(元素篩選,分到兩個數組)
sortedUniq (去重,排序)
takeRightWhile ( 從
array
數組的最後一個元素開始提取元素,直到predicate
返回假值 )uniqBy (去重,排序)
四、集合 Collection
Collection很多API都能讓人眼前一亮,在實際開發中都能得到應用。
forEach(遍歷數組或對象) | forEachRight(反序遍歷數組或對象)
// 遍歷數組有點多餘
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)
})
every(每個元素都符合條件)| some(某個元素符合條件)| filter(過濾)| find(查找第一個)| findLast(查找最後一個)| includes(抱哈某個元素)。亮點:可以傳入一個對象進行匹配
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
groupBy(分組)
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 (打亂)
五、函數 Function
下面列舉的是實際開發中應用場景較多的API,具體的用法就不做demo了,具體可參看官網API。
after(n, func) :調用執行n次後才能執行func
before(n, func):調用n次後不再執行func,n次後的返回值爲第n次返回值
curry | curryRight :柯里化
debounce :防抖
defer :推遲調用
func
,直到當前堆棧清理完畢throttle :節流
unary :創建一個最多接受一個參數的函數,忽略多餘的參數
六、Lang
Lang下多爲判斷類型的API,常規的isXxx判斷類型API就不做過多的介紹。下面介紹一些好用的API。
克隆系列:clone、cloneDeep、cloneWith、cloneDeepWith
eq :判斷相等,能判斷NaN
isEqual :判斷兩個對象可枚舉value相等,注意不能用於對比DOM對象
isEqualWith:定製isEqual比較
isMatch :判斷兩個對象部分可枚舉value相等
isMatchWith :定製isMatch比較
七、數學 Math
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'
八、數字 Number
inRange:判斷大於等於且小於等於。改進實現isInRange
/**
* 判斷數字是否在某個區間
* @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
九、對象 Object
下面只記錄讓人眼前一亮的API
at | get :字符串key鏈路取值
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
defaultsDeep :深層設置默認值
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}}
has | hasIn :判斷是否有屬性鏈。有時候爲了避免代碼報錯,需要進行串聯取值:
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' },
}
*/
omit | omitBy :剔除對象屬性。用在抽取保存到後端數據,後端校驗嚴格,不能有多餘字段等場景。
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對應
十、Seq
API過多,下面只記錄Seq讓人眼前一亮的API
chain :解決lodash不能鏈式調用
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
十一、字符串 String
lodash的String API多爲轉換不同值的API,如:首字母大寫、駝峯式、html屬性式、下劃線連接式、全小寫、首字母小寫、編碼、填充,去空格等API。
唯一亮眼的API:template(字符串模板)。可應用於 動態國際化、拼接國際化較優實現
const compiled = lodash.template('hello <%= user.name %>!')
console.log(compiled({ user: { name: 'fred' } }))
// hello fred!
最後
如果你覺得這篇內容對你挺有啓發,我想邀請你幫我三個小忙:
點個「在看」,讓更多的人也能看到這篇內容(喜歡不點在看,都是耍流氓 -_-)
歡迎加我微信「qianyu443033099」拉你進技術羣,長期交流學習...
關注公衆號「前端下午茶」,持續爲你推送精選好文,也可以加我爲好友,隨時聊騷。
點個在看支持我吧,轉發就更好了