天天看點

Lodash 擴充JS通用方法

版權聲明:本文首發 http://asing1elife.com ,轉載請注明出處。 https://blog.csdn.net/asing1elife/article/details/82848345

Lodash是一個著名的javascript原生庫,不需要引入其他第三方依賴。是一個意在提高開發者效率,提高JS原生方法性能的JS庫

更多精彩

官網

  1. Lodash Documentation
  2. lodash 中文文檔

文法

集合[Collection]

  1. _.find

    在集合中擷取到指定元素
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
]
 
// 自定義比對規則
_.find(users, function(o) { return o.age < 40; })
                
  1. _.filter

    擷取集合中滿足條件的元素集
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
]
 
// => { 'user': 'fred',   'age': 40, 'active': false }
_.filter(users, function(o) { return !o.active; })
                

數組[Array]

  1. _.findIndex

    在數組中擷取指定元素的索引
    • 比對的規則可自定義
    • 比對到則傳回對應索引,否則傳回-1
let fileType = currentFile.type

let currentIndex = _.findIndex(this.types, function (type) {
	return fileType.toLowerCase().match(new RegExp(type))
})
                
  1. _.unionWith

    連接配接兩個數組
    • 連接配接的規則可自定義
    • 規則傳回true的則跳過
this.examPaper.examQuestions = _.unionWith(this.examPaper.examQuestions, this.selectQuestions, (a, b) => {
  return a.hexId === b.hexId
})
                
  1. _.drop

    移除數組元素
    • 預設移除第一個元素
    • 可顯式指定從第幾個元素開始移除
_.drop(this.userWorkIds)
                

繼續閱讀