Lodash 快速指南



Lodash - 概述

Lodash是一個流行的基於JavaScript的庫,它提供200多個函式來簡化Web開發。它提供諸如map、filter、invoke之類的輔助函式,以及函式繫結、JavaScript模板、深度相等性檢查、建立索引等等。Lodash可以直接在瀏覽器中使用,也可以與Node.js一起使用。

使用JavaScript操作物件可能非常具有挑戰性,特別是如果您需要對它們進行大量操作。Lodash提供了許多功能,可以簡化您對物件的處理。

Lodash是一個開源專案,您可以輕鬆地為該庫貢獻程式碼並新增功能(以外掛的形式),並在GitHub和Node.js上提供。

特性

讓我們詳細瞭解Lodash提供的所有重要特性:

集合

Lodash為集合提供了各種函式,例如each、map、reduce,這些函式用於對集合的每個專案應用操作。它提供了諸如groupBy、countBy、max、min之類的處理集合的方法,簡化了許多工。

陣列

Lodash提供了各種陣列函式,用於迭代和處理陣列,例如first、initial、lastIndexOf、intersection、difference等。

函式

Lodash提供諸如bind、delay、before、after等函式。

物件

Lodash提供用於操作物件、對映物件和比較物件的函式。例如,keys、values、extend、extendOwn、isEqual、isEmpty等。

工具

Lodash提供了各種實用程式方法,例如noConflict、random、iteratee、escape等。

鏈式呼叫

Lodash還提供鏈式呼叫方法,例如chain、value。

在後續章節中,我們將介紹Lodash的重要函式。

Lodash - 環境搭建

在本節中,您將詳細瞭解如何在本地計算機上設定Lodash的工作環境。在開始使用Lodash之前,您需要訪問該庫。您可以透過以下任何一種方法訪問其檔案:

方法一:在瀏覽器中使用Lodash檔案

在這種方法中,我們將從其官方網站獲取Lodash檔案,並直接在瀏覽器中使用它。

步驟一

第一步,訪問Lodash的官方網站 https://lodash.com/

您可以看到一個下載選項,它提供最新的lodash.min.js檔案,以及可用的CDN副本。點選連結並選擇lodash.min.js的最新連結。

步驟二

現在,在script標籤內包含lodash.min.js,並開始使用Lodash。為此,您可以使用以下程式碼:

<script type = "text/JavaScript" 
   src = "https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js">
</script>

這裡給出一個工作示例及其輸出,以便更好地理解:

示例

<html>
   <head>
      <title>Lodash - Working Example</title>
      <script type = "text/JavaScript" src = "https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
      <style>
         div {
            border: solid 1px #ccc;
            padding:10px;
            font-family: "Segoe UI",Arial,sans-serif;
            width: 50%;
         }
      </style>
   </head>
   <body>
      <div style = "font-size:25px" id = "list"></div>
      <script type = "text/JavaScript">
         var numbers = [1, 2, 3, 4];
         var listOfNumbers = '';
         _.each(numbers, function(x) { listOfNumbers += x + ' ' });
         document.getElementById("list").innerHTML = listOfNumbers;
      </script>
   </body>
</html>

輸出

方法二:使用Node.js

如果您選擇此方法,請確保您的系統上已安裝Node.jsnpm。您可以使用以下命令安裝Lodash:

npm install lodash

Lodash成功安裝後,您可以看到以下輸出:

+ lodash@4.17.20
added 1 package from 2 contributors and audited 1 package in 2.54s
found 0 vulnerabilities

現在,要測試Lodash是否與Node.js正常工作,請建立檔案tester.js並將以下程式碼新增到其中:

var _ = require('lodash');
var numbers = [1, 2, 3, 4];
var listOfNumbers = '';
_.each(numbers, function(x) { listOfNumbers += x + ' ' });
console.log(listOfNumbers);

將上述程式儲存到tester.js中。使用以下命令編譯和執行此程式。

命令

\>node tester.js

輸出

1 2 3 4

Lodash - 陣列

Lodash有很多易於使用的處理陣列的方法。本章將詳細介紹它們。

Lodash 提供了各種處理陣列的方法,如下所示:

序號 方法及語法
1

chunk

_.chunk(array, [size=1])

2

compact

_.compact(array)

3

concat

_.concat(array, [values])

4

difference

_.difference(array, [values])

5

differenceBy

_.differenceBy(array, [values], [iteratee=_.identity])

6

differenceWith

_.differenceWith(array, [values], [comparator])

7

drop

_.drop(array, [n=1])

8

dropRight

_.dropRight(array, [n=1])

9

dropRightWhile

_.dropRightWhile(array, [predicate=_.identity])

10

dropWhile

_.dropWhile(array, [predicate=_.identity])

11

fill

_.fill(array, value, [start=0], [end=array.length])

12

findIndex

_.findIndex(array, [predicate=_.identity], [fromIndex=0])

13

findLastIndex

_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])

14

flatten

_.flatten(array)

15

flattenDeep

_.flattenDeep(array)

16

flattenDepth

_.flattenDepth(array, [depth=1])

17

fromPairs

_.fromPairs(pairs)

18

head

_.head(array)

19

indexOf

_.indexOf(array, value, [fromIndex=0])

20

initial

_.initial(array)

21

intersection

_.intersection([arrays])

22

intersectionBy

_.intersectionBy([arrays], [iteratee=_.identity])

23

intersectionWith

_.intersectionWith([arrays], [comparator])

24

join

_.join(array, [separator=','])

25

last

_.last(array)

26

lastIndexOf

_.lastIndexOf(array, value, [fromIndex=array.length-1])

27

nth

_.nth(array, [n=0])

28

pull

_.pull(array, [values])

29

pullAll

_.pullAll(array, values)

30

pullAllBy

_.pullAllBy(array, values, [iteratee=_.identity])

31

pullAllWith

_.pullAllWith(array, values, [comparator])

32

pullAt

_.pullAt(array, [indexes])

33

remove

_.remove(array, [predicate=_.identity])

34

reverse

_.reverse(array)

35

slice

_.slice(array, [start=0], [end=array.length])

36

sortedIndex

_.sortedIndex(array, value)

37

sortedIndexBy

_.sortedIndexBy(array, value, [iteratee=_.identity])

38

sortedIndexOf

_.sortedIndexOf(array, value)

39

sortedLastIndex

_.sortedLastIndex(array, value)

40

sortedLastIndexBy

_.sortedLastIndexBy(array, value, [iteratee=_.identity])

41

sortedLastIndexOf

_.sortedLastIndexOf(array, value)

42

sortedUniq

_.sortedUniq(array)

43

sortedUniqBy

_.sortedUniqBy(array, [iteratee])

44

tail

_.tail(array)

45

take

_.take(array, [n=1])

46

takeRight

_.takeRight(array, [n=1])

47

takeRightWhile

_.takeRightWhile(array, [predicate=_.identity])

48

takeWhile

_.takeWhile(array, [predicate=_.identity])

49

union

_.union([arrays])

50

unionBy

_.unionBy([arrays], [iteratee=_.identity])

51

unionWith

_.unionWith([arrays], [comparator])

52

uniq

_.uniq(array)

53

uniqBy

_.uniqBy(array, [iteratee=_.identity])

54

uniqWith

_.uniqWith(array, [comparator])

55

unzip

_.unzip(array)

56

unzipwith

_.unzipWith(array, [iteratee=_.identity])

57

without

_.without(array, [values])

58

xor

_.xor([arrays])

59

xorBy

_.xorBy([arrays], [iteratee=_.identity])

60

xorWith

_.xorWith([arrays], [comparator])

61

zip

_.zip([arrays])

62

zipObject

_.zipObject([props=[]], [values=[]])

63

zipObjectDeep

_.zipObjectDeep([props=[]], [values=[]])

64

zipWith

_.zipWith([arrays], [iteratee=_.identity])

Lodash - 集合

Lodash有很多易於使用的處理集合的方法。本章將詳細介紹它們。

Lodash 提供了各種處理集合的方法,如下所示:

序號 方法及語法
1

countBy

_.countBy(collection, [iteratee=_.identity])

2

every

_.every(collection, [predicate=_.identity])

3

filter

_.filter(collection, [predicate=_.identity])

4

find

_.find(collection, [predicate=_.identity], [fromIndex=0])

5

findLast

_.findLast(collection, [predicate=_.identity], [fromIndex=collection.length-1])

6

flatMap

_.flatMap(collection, [iteratee=_.identity])

7

flatMapDeep

_.flatMapDeep(collection, [iteratee=_.identity])

8

flatMapDepth

_.flatMapDepth(collection, [iteratee=_.identity], [depth=1])

9

forEach

_.forEach(collection, [iteratee=_.identity])

10

forEachRight

_.forEachRight(collection, [iteratee=_.identity])

11

groupBy

_.groupBy(collection, [iteratee=_.identity])

12

includes

_.includes(collection, value, [fromIndex=0])

13

invokeMap

_.invokeMap(collection, path, [args])

14

keyBy

_.keyBy(collection, [iteratee=_.identity])

15

map

_.map(collection, [iteratee=_.identity])

16

orderBy

_.orderBy(collection, [iteratees=[_.identity]], [orders])

17

partition

_.partition(collection, [predicate=_.identity])

18

reduce

_.reduce(collection, [iteratee=_.identity], [accumulator])

19

reduceRight

_.reduceRight(collection, [iteratee=_.identity], [accumulator])

20

reject

_.reject(collection, [predicate=_.identity])

21

sample

_.sample(collection)

22

sampleSize

_.sampleSize(collection, [n=1])

23

shuffle

_.shuffle(collection)

24

size

_.size(collection)

25

some

_.some(collection, [predicate=_.identity])

26

sortBy

_.sortBy(collection, [iteratees=[_.identity]])

Lodash - 日期

Lodash 提供了一個 now 函式,用於獲取當前時間的毫秒數。

語法

_.now()

獲取自 Unix 紀元 (1970 年 1 月 1 日 00:00:00 UTC) 以來經過的毫秒數的時間戳。

輸出

  • (number) - 返回時間戳。

示例

var _ = require('lodash');
var result = _.now();
console.log(result);

將上述程式儲存到 **tester.js** 中。執行以下命令執行此程式。

命令

\>node tester.js

輸出

1601614929848

Lodash - 函式

Lodash 有很多易於使用的建立和處理函式的方法。本章將詳細介紹它們。

Lodash 提供了各種處理函式的方法,如下所示:

序號 方法及語法
1

ary

_.ary(func, [n=func.length])

2

before

_.before(n, func)

3

bind

_.bind(func, thisArg, [partials])

4

bindKey

_.bindKey(object, key, [partials])

5

curry

_.curry(func, [arity=func.length])

6

curryRight

_.curryRight(func, [arity=func.length])

7

delay

_.delay(func, wait, [args])

8

flip

_.flip(func)

9

memoize

_.memoize(func, [resolver])

10

negate

_.negate(predicate)

11

once

_.once(func)

12

overArgs

_.overArgs(func, [transforms=[_.identity]])

13

partial

_.partial(func, [partials])

14

partialRight

_.partialRight(func, [partials])

15

rearg

_.rearg(func, indexes)

16

rest

_.rest(func, [start=func.length-1])

17

spread

_.spread(func, [start=0])

18

unary

_.unary(func)

19

wrap

_.wrap(value, [wrapper=identity])

Lodash - Lang (語言)

Lodash 有許多易於使用的通用方法。本章將詳細介紹它們。

Lodash 提供了各種通用方法,如下所示:

序號 方法及語法
1

castArray

_.castArray(value)

2

clone

_.clone(value)

3

cloneDeep

_.cloneDeep(value)

4

conformsTo

_.conformsTo(object, source)

5

eq

_.eq(value, other)

6

gt

_.gt(value, other)

7

gte

_.gte(value, other)

8

isArguments

_.isArguments(value)

9

isArray

_.isArray(value)

10

isArrayBuffer

_.isArrayBuffer(value)

11

isArrayLike

_.isArrayLike(value)

12

isArrayLikeObject

_.isArrayLikeObject(value)

13

isBoolean

_.isBoolean(value)

14

isBuffer

_.isBuffer(value)

15

isDate

_.isDate(value)

16

isEmpty

_.isEmpty(value)

17

isEqual

_.isEqual(value, other)

18

isEqualWith

_.isEqualWith(value, other, [customizer])

19

isError

_.isError(value)

20

isFinite

_.isFinite(value)

21

isFunction

_.isFunction(value)

22

isInteger

_.isInteger(value)

23

isLength

_.isLength(value)

24

isMap

_.isMap(value)

25

isMatch

_.isMatch(object, source)

26

isMatchWith

_.isMatchWith(object, source, [customizer])

27

isNaN

_.isNaN(value)

28

isNative

_.isNative(value)

29

isNil

_.isNil(value)

30

isNull

_.isNull(value)

31

isNumber

_.isNumber(value)

32

isObject

_.isObject(value)

33

isObjectLike

_.isObjectLike(value)

34

isPlainObject

_.isPlainObject(value)

35

isRegExp

_.isRegExp(value)

36

isSafeInteger

_.isSafeInteger(value)

37

isSet

_.isSet(value)

38

isString

_.isString(value)

39

isSymbol

_.isSymbol(value)

40

isTypedArray

_.isTypedArray(value)

41

isUndefined

_.isUndefined(value)

42

isWeakMap

_.isWeakMap(value)

43

isWeakSet

_.isWeakSet(value)

44

lt

_.lt(value, other)

45

lte

_.lte(value, other)

46

toArray

_.toArray(value)

47

toFinite

_.toFinite(value)

48

toInteger

_.toInteger(value)

49

toLength

_.toLength(value)

50

toNumber

_.toNumber(value)

51

toPlainObject

_.toPlainObject(value)

52

toSafeInteger

_.toSafeInteger(value)

53

toString

_.toString(value)

Lodash - Math (數學)

Lodash擁有許多易於使用的數學相關方法。本章將詳細討論它們。

Lodash提供各種數學相關方法,如下所示:

序號 方法及語法
1

add

_.add(augend, addend)

2

ceil

_.ceil(number, [precision=0])

3

divide

_.divide(dividend, divisor)

4

floor

_.floor(number, [precision=0])

5

max

_.max(array)

6

maxBy

_.maxBy(array, [iteratee=_.identity])

7

mean

_.mean(array)

8

meanBy

_.meanBy(array, [iteratee=_.identity])

9

min

_.min(array)

10

minBy

_.minBy(array, [iteratee=_.identity])

11

multiply

_.multiply(multiplier, multiplicand)

12

round

_.round(number, [precision=0])

13

subtract

_.subtract(minuend, subtrahend)

14

sum

_.sum(array)

15

sumBy

_.sumBy(array, [iteratee=_.identity])

Lodash - 數字

Lodash擁有許多易於使用的數字相關方法。本章將詳細討論它們。

Lodash提供各種數字相關方法,如下所示:

序號 方法及語法
1

clamp

_.clamp(number, [lower], upper)

2

inRange

_.inRange(number, [start=0], end)

3

random

_.random([lower=0], [upper=1], [floating])

Lodash - 物件

Lodash擁有許多易於使用的物件相關方法。本章將詳細討論它們。

Lodash提供各種物件相關方法,如下所示:

序號 方法及語法
1

assign

_.assign(object, [sources])

2

assignIn

_.assignIn(object, [sources])

3

assignInWith

_.assignInWith(object, sources, [customizer])

4

assignWith

_.assignWith(object, sources, [customizer])

5

at

_.at(object, [paths])

6

create

_.create(prototype, [properties])

7

defaults

_.defaults(object, [sources])

8

defaultsDeep

_.defaultsDeep(object, [sources])

9

findKey

_.findKey(object, [predicate=_.identity])

10

findLastKey

_.findLastKey(object, [predicate=_.identity])

11

forIn

_.forIn(object, [iteratee=_.identity])

12

forInRight

_.forInRight(object, [iteratee=_.identity])

13

forOwn

_.forOwn(object, [iteratee=_.identity])

14

forOwnRight

_.forOwnRight(object, [iteratee=_.identity])

15

functions

_.functions(object)

16

functionsIn

_.functionsIn(object)

17

get

_.get(object, path, [defaultValue])

18

has

_.has(object, path)

19

hasIn

_.hasIn(object, path)

20

invert

_.invert(object)

21

invertBy

_.invertBy(object, [iteratee=_.identity])

22

invoke

_.invoke(object, path, [args])

23

keys

_.keys(object)

24

keysIn

_.keysIn(object)

25

mapKeys

_.mapKeys(object, [iteratee=_.identity])

26

mapValues

_.mapValues(object, [iteratee=_.identity])

27

merge

_.merge(object, [sources])

28

mergeWith

_.mergeWith(object, sources, customizer)

29

omit

_.omit(object, [paths])

30

omitBy

_.omitBy(object, [predicate=_.identity])

31

pick

_.pick(object, [paths])

32

pickBy

_.pickBy(object, [predicate=_.identity])

33

result

_.result(object, path, [defaultValue])

34

set

_.set(object, path, value)

35

setWith

_.setWith(object, path, value, [customizer])

36

toPairs

_.toPairs(object)

37

toPairsIn

_.toPairsIn(object)

38

transform

_.transform(object, [iteratee=_.identity], [accumulator])

39

unset

_.unset(object, path)

40

update

_.update(object, path, updater)

41

updateWith

_.updateWith(object, path, updater, [customizer])

42

values

_.values(object)

43

valuesIn

_.valuesIn(object)

Lodash - Seq (序列)

Lodash擁有許多易於使用的序列相關方法。本章將詳細討論它們。

Lodash提供各種序列相關方法,如下所示:

序號 方法及語法
1

chain

_.chain(value)

2

tap

_.tap(value, interceptor)

3

thru

_.thru(value, interceptor)

4

prototype[Symbol.iterator]

_.prototype[Symbol.iterator]()

5

prototype.at

_.prototype.at([paths])

6

prototype.chain

_.prototype.chain()

7

prototype.commit

_.prototype.commit()

8

prototype.next

_.prototype.next()

9

prototype.plant

_.prototype.plant(value)

10

prototype.reverse

_.prototype.reverse()

11

prototype.value

_.prototype.value()

Lodash - 字串

Lodash擁有許多易於使用的字串操作方法。本章將詳細討論它們。

Lodash提供各種字串相關方法,如下所示:

序號 方法及語法
1

camelCase

_.camelCase([string=''])

2

capitalize

_.capitalize([string=''])

3

deburr

_.deburr([string=''])

4

endsWith

_.endsWith([string=''], [target], [position=string.length])

5

escape

_.escape([string=''])

6

escapeRegExp

_.escapeRegExp([string=''])

7

kebabCase

_.kebabCase([string=''])

8

lowerCase

_.lowerCase([string=''])

9

lowerFirst

_.lowerFirst([string=''])

10

pad

_.pad([string=''], [length=0], [chars=' '])

11

padEnd

_.padEnd([string=''], [length=0], [chars=' '])

12

padStart

_.padStart([string=''], [length=0], [chars=' '])

13

parseInt

_.parseInt(string, [radix=10])

14

repeat

_.repeat([string=''], [n=1])

15

replace

_.replace([string=''], pattern, replacement)

16

snakeCase

_.snakeCase([string=''])

17

split

_.split([string=''], separator, [limit])

18

startCase

_.startCase([string=''])

19

startsWith

_.startsWith([string=''], [target], [position=0])

20

template

_.template([string=''], [options={}])

21

toLower

_.toLower([string=''])

22

toUpper

_.toUpper([string=''])

23

trim

_.trim([string=''], [chars=whitespace])

24

trimEnd

_.trimEnd([string=''], [chars=whitespace])

25

trimStart

_.trimStart([string=''], [chars=whitespace])

26

truncate

_.truncate([string=''], [options={}])

27

unescape

_.unescape([string=''])

28

upperCase

_.upperCase([string=''])

29

upperFirst

_.upperFirst([string=''])

30

words

_.words([string=''], [pattern])

Lodash - Util (工具)

Lodash擁有許多易於使用的實用程式方法。本章將詳細討論它們。

Lodash提供各種實用程式方法,如下所示:

序號 方法及語法
1

cond

_.cond(pairs)

2

conforms

_.conforms(source)

3

constant

_.constant(value)

4

defaultTo

_.defaultTo(value, defaultValue)

5

flow

_.flow([funcs])

6

flowRight

_.flowRight([funcs])

7

identity

_.identity(value)

8

iteratee

_.iteratee([func=_.identity])

9

matches

_.matches(source)

10

matchesProperty

_.matchesProperty(path, srcValue)

11

method

_.method(path, [args])

12

methodOf

_.methodOf(object, [args])

13

mixin

_.mixin([object=lodash], source, [options={}])

14

noConflict

_.noConflict()

15

noop

_.noop()

16

nthArg

_.nthArg([n=0])

17

over

_.over([iteratees=[_.identity]])

18

overEvery

_.overEvery([predicates=[_.identity]])

19

overSome

_.overSome([predicates=[_.identity]])

20

property

_.property(path)

21

propertyOf

_.propertyOf(object)

22

range

_.range([start=0], end, [step=1])

23

rangeRight

_.rangeRight([start=0], end, [step=1])

24

runInContext

_.runInContext([context=root])

25

stubArray

_.stubArray()

26

stubFalse

_.stubFalse()

27

stubObject

_.stubObject()

28

stubString

_.stubString()

29

stubTrue

_.stubTrue()

30

times

_.times(n, [iteratee=_.identity])

31

toPath

_.toPath(value)

32

uniqueId

_.uniqueId([prefix=''])

Lodash - 屬性

本章詳細討論Lodash屬性。

序號 方法及語法
1

_.VERSION − (字串): 語義版本號。

2

_.templateSettings − (物件): 預設情況下,Lodash使用的模板分隔符類似於嵌入式Ruby (ERB)以及ES2015模板字串。更改以下模板設定以使用替代分隔符。

3

_.templateSettings.escape − (正則表示式): 用於檢測需要HTML轉義的資料屬性值。

4

_.templateSettings.evaluate − (正則表示式): 用於檢測要計算的程式碼。

5

_.templateSettings.imports − (物件): 用於將變數匯入編譯後的模板。

6

_.templateSettings.interpolate − (正則表示式): 用於檢測要注入的資料屬性值。

7

_.templateSettings.variable − (字串): 用於在模板文字中引用資料物件。

Lodash - 方法

本章詳細討論Lodash屬性。

序號 方法及語法
1

_.VERSION − (字串): 語義版本號。

2

_.templateSettings − (物件): 預設情況下,Lodash使用的模板分隔符類似於嵌入式Ruby (ERB)以及ES2015模板字串。更改以下模板設定以使用替代分隔符。

3

_.templateSettings.escape − (正則表示式): 用於檢測需要HTML轉義的資料屬性值。

4

_.templateSettings.evaluate − (正則表示式): 用於檢測要計算的程式碼。

5

_.templateSettings.imports − (物件): 用於將變數匯入編譯後的模板。

6

_.templateSettings.interpolate − (正則表示式): 用於檢測要注入的資料屬性值。

7

_.templateSettings.variable − (字串): 用於在模板文字中引用資料物件。

廣告
© . All rights reserved.