陣列
_.chunk
_.compact
_.concat
_.difference
_.differenceBy
_.differenceWith
_.drop
_.dropRight
_.dropRightWhile
_.dropWhile
_.fill
_.findIndex
_.findLastIndex
_.first
-> head
_.flatten
_.flattenDeep
_.flattenDepth
_.fromPairs
_.head
_.indexOf
_.initial
_.intersection
_.intersectionBy
_.intersectionWith
_.join
_.last
_.lastIndexOf
_.nth
_.pull
_.pullAll
_.pullAllBy
_.pullAllWith
_.pullAt
_.remove
_.reverse
_.slice
_.sortedIndex
_.sortedIndexBy
_.sortedIndexOf
_.sortedLastIndex
_.sortedLastIndexBy
_.sortedLastIndexOf
_.sortedUniq
_.sortedUniqBy
_.tail
_.take
_.takeRight
_.takeRightWhile
_.takeWhile
_.union
_.unionBy
_.unionWith
_.uniq
_.uniqBy
_.uniqWith
_.unzip
_.unzipWith
_.without
_.xor
_.xorBy
_.xorWith
_.zip
_.zipObject
_.zipObjectDeep
_.zipWith
集合
Date
Function
Lang
_.castArray
_.clone
_.cloneDeep
_.cloneDeepWith
_.cloneWith
_.conformsTo
_.eq
_.gt
_.gte
_.isArguments
_.isArray
_.isArrayBuffer
_.isArrayLike
_.isArrayLikeObject
_.isBoolean
_.isBuffer
_.isDate
_.isElement
_.isEmpty
_.isEqual
_.isEqualWith
_.isError
_.isFinite
_.isFunction
_.isInteger
_.isLength
_.isMap
_.isMatch
_.isMatchWith
_.isNaN
_.isNative
_.isNil
_.isNull
_.isNumber
_.isObject
_.isObjectLike
_.isPlainObject
_.isRegExp
_.isSafeInteger
_.isSet
_.isString
_.isSymbol
_.isTypedArray
_.isUndefined
_.isWeakMap
_.isWeakSet
_.lt
_.lte
_.toArray
_.toFinite
_.toInteger
_.toLength
_.toNumber
_.toPlainObject
_.toSafeInteger
_.toString
Math
Object
_.assign
_.assignIn
_.assignInWith
_.assignWith
_.at
_.create
_.defaults
_.defaultsDeep
_.entries
-> toPairs
_.entriesIn
-> toPairsIn
_.extend
-> assignIn
_.extendWith
-> assignInWith
_.findKey
_.findLastKey
_.forIn
_.forInRight
_.forOwn
_.forOwnRight
_.functions
_.functionsIn
_.get
_.has
_.hasIn
_.invert
_.invertBy
_.invoke
_.keys
_.keysIn
_.mapKeys
_.mapValues
_.merge
_.mergeWith
_.omit
_.omitBy
_.pick
_.pickBy
_.result
_.set
_.setWith
_.toPairs
_.toPairsIn
_.transform
_.unset
_.update
_.updateWith
_.values
_.valuesIn
Seq
字串
工具
_.attempt
_.bindAll
_.cond
_.conforms
_.constant
_.defaultTo
_.flow
_.flowRight
_.identity
_.iteratee
_.matches
_.matchesProperty
_.method
_.methodOf
_.mixin
_.noConflict
_.noop
_.nthArg
_.over
_.overEvery
_.overSome
_.property
_.propertyOf
_.range
_.rangeRight
_.runInContext
_.stubArray
_.stubFalse
_.stubObject
_.stubString
_.stubTrue
_.times
_.toPath
_.uniqueId
屬性
「陣列」方法
_.chunk(array, [size=1])
建立一個陣列,將元素分割成長度為 size
的群組。如果 array
無法平均分割,最後一個區塊將會是剩餘的元素。
3.0.0
array
(Array): 要處理的陣列。[size=1]
(number): 每個區塊的長度(Array): 傳回新的區塊陣列。
_.chunk(['a', 'b', 'c', 'd'], 2);// => [['a', 'b'], ['c', 'd']] _.chunk(['a', 'b', 'c', 'd'], 3);// => [['a', 'b', 'c'], ['d']]
_.compact(array)
建立一個移除所有假值的新陣列。假值包括 false
、null
、0
、""
、undefined
和 NaN
。
0.1.0
array
(陣列): 要壓縮的陣列。(陣列): 傳回過濾後的新陣列。
_.compact([0, 1, false, 2, '', 3]);// => [1, 2, 3]
_.concat(array, [values])
建立一個新陣列,將 array
與任何其他陣列和/或值串接。
4.0.0
array
(陣列): 要串接的陣列。[values]
(...*): 要串接的值。(陣列): 傳回串接後的新陣列。
var array = [1];var other = _.concat(array, 2, [3], [[4]]); console.log(other);// => [1, 2, 3, [4]] console.log(array);// => [1]
_.difference(array, [values])
使用 SameValueZero
進行相等性比較,建立一個 array
值的陣列,其中不包含其他給定陣列中的值。結果值的順序和參考取決於第一個陣列。
注意:與 _.pullAll
不同,此方法會傳回一個新陣列。
0.1.0
陣列
(陣列):要檢查的陣列。[值]
(...陣列):要排除的值。(陣列): 傳回過濾後的新陣列。
_.difference([2, 1], [2, 3]);// => [1]
_.differenceBy(array, [values], [iteratee=_.identity])
此方法類似於 _.difference
,但它會接受 iteratee
,並針對 array
和 values
的每個元素呼叫它,以產生用於比較它們的準則。結果值的順序和參考是由第一個陣列決定的。iteratee 會以一個引數呼叫
(value).
注意:與 _.pullAllBy
不同,此方法會傳回一個新的陣列。
4.0.0
陣列
(陣列):要檢查的陣列。[值]
(...陣列):要排除的值。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(陣列): 傳回過濾後的新陣列。
_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);// => [1.2] // The `_.property` iteratee shorthand._.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');// => [{ 'x': 2 }]
_.differenceWith(array, [values], [comparator])
此方法類似於 _.difference
,但它會接受 comparator
,並呼叫它來比較 array
和 values
的元素。結果值的順序和參考是由第一個陣列決定的。comparator 會以兩個引數呼叫:(arrVal, othVal)。
注意:與 _.pullAllWith
不同,此方法會傳回一個新的陣列。
4.0.0
陣列
(陣列):要檢查的陣列。[值]
(...陣列):要排除的值。[comparator]
(函式):每個元素呼叫的 comparator。(陣列): 傳回過濾後的新陣列。
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);// => [{ 'x': 2, 'y': 1 }]
_.drop(array, [n=1])
建立一個 array
的切片,從開頭捨棄 n
個元素。
0.5.0
array
(陣列):要查詢的陣列。[n=1]
(數字):要捨棄的元素數量。(陣列):傳回 array
的切片。
_.drop([1, 2, 3]);// => [2, 3] _.drop([1, 2, 3], 2);// => [3] _.drop([1, 2, 3], 5);// => [] _.drop([1, 2, 3], 0);// => [1, 2, 3]
_.dropRight(array, [n=1])
建立一個 array
的切片,從結尾捨棄 n
個元素。
3.0.0
array
(陣列):要查詢的陣列。[n=1]
(數字):要捨棄的元素數量。(陣列):傳回 array
的切片。
_.dropRight([1, 2, 3]);// => [1, 2] _.dropRight([1, 2, 3], 2);// => [1] _.dropRight([1, 2, 3], 5);// => [] _.dropRight([1, 2, 3], 0);// => [1, 2, 3]
_.dropRightWhile(array, [predicate=_.identity])
建立一個 array
的切片,排除從結尾捨棄的元素。元素會捨棄直到 predicate
傳回假值。此謂詞會呼叫三個參數:(value, index, array)。
3.0.0
array
(陣列):要查詢的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回 array
的切片。
var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; _.dropRightWhile(users, function(o) { return !o.active; });// => objects for ['barney'] // The `_.matches` iteratee shorthand._.dropRightWhile(users, { 'user': 'pebbles', 'active': false });// => objects for ['barney', 'fred'] // The `_.matchesProperty` iteratee shorthand._.dropRightWhile(users, ['active', false]);// => objects for ['barney'] // The `_.property` iteratee shorthand._.dropRightWhile(users, 'active');// => objects for ['barney', 'fred', 'pebbles']
_.dropWhile(array, [predicate=_.identity])
建立一個 array
的切片,排除從開頭捨棄的元素。元素會捨棄直到 predicate
傳回假值。此謂詞會呼叫三個參數:(value, index, array)。
3.0.0
array
(陣列):要查詢的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回 array
的切片。
var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true }]; _.dropWhile(users, function(o) { return !o.active; });// => objects for ['pebbles'] // The `_.matches` iteratee shorthand._.dropWhile(users, { 'user': 'barney', 'active': false });// => objects for ['fred', 'pebbles'] // The `_.matchesProperty` iteratee shorthand._.dropWhile(users, ['active', false]);// => objects for ['pebbles'] // The `_.property` iteratee shorthand._.dropWhile(users, 'active');// => objects for ['barney', 'fred', 'pebbles']
_.fill(array, value, [start=0], [end=array.length])
使用 value
填入 array
的元素,從 start
開始,但不包含 end
。
注意:此方法會變更 array
。
3.2.0
array
(陣列):要填入的陣列。value
(*):用於填入 array
的值。[start=0]
(數字):開始位置。[end=array.length]
(數字):結束位置。(陣列):傳回 array
。
var array = [1, 2, 3]; _.fill(array, 'a');console.log(array);// => ['a', 'a', 'a'] _.fill(Array(3), 2);// => [2, 2, 2] _.fill([4, 6, 8, 10], '*', 1, 3);// => [4, '*', '*', 10]
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
此方法類似於 _.find
,但它會傳回 predicate
傳回真值的元素的第一個索引,而不是元素本身。
1.1.0
陣列
(陣列):要檢查的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。[fromIndex=0]
(數字):開始搜尋的索引。(數字):傳回找到的元素的索引,否則傳回 -1
。
var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true }]; _.findIndex(users, function(o) { return o.user == 'barney'; });// => 0 // The `_.matches` iteratee shorthand._.findIndex(users, { 'user': 'fred', 'active': false });// => 1 // The `_.matchesProperty` iteratee shorthand._.findIndex(users, ['active', false]);// => 0 // The `_.property` iteratee shorthand._.findIndex(users, 'active');// => 2
_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])
此方法類似於 _.findIndex
,但它會從右至左迭代 collection
的元素。
2.0.0
陣列
(陣列):要檢查的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。[fromIndex=array.length-1]
(數字):開始搜尋的索引。(數字):傳回找到的元素的索引,否則傳回 -1
。
var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });// => 2 // The `_.matches` iteratee shorthand._.findLastIndex(users, { 'user': 'barney', 'active': true });// => 0 // The `_.matchesProperty` iteratee shorthand._.findLastIndex(users, ['active', false]);// => 2 // The `_.property` iteratee shorthand._.findLastIndex(users, 'active');// => 0
_.flatten(array)
將 array
展平一層。
0.1.0
array
(陣列):要展平的陣列。(陣列):傳回新的扁平陣列。
_.flatten([1, [2, [3, [4]], 5]]);// => [1, 2, [3, [4]], 5]
_.flattenDeep(array)
遞迴扁平化 array
。
3.0.0
array
(陣列):要展平的陣列。(陣列):傳回新的扁平陣列。
_.flattenDeep([1, [2, [3, [4]], 5]]);// => [1, 2, 3, 4, 5]
_.flattenDepth(array, [depth=1])
遞迴扁平化 array
最多 depth
次。
4.4.0
array
(陣列):要展平的陣列。[depth=1]
(數字):最大遞迴深度。(陣列):傳回新的扁平陣列。
var array = [1, [2, [3, [4]], 5]]; _.flattenDepth(array, 1);// => [1, 2, [3, [4]], 5] _.flattenDepth(array, 2);// => [1, 2, 3, [4], 5]
_.fromPairs(pairs)
_.toPairs
的反函式;此方法傳回一個由 key-value pairs
組成的物件。
4.0.0
pairs
(陣列):key-value 成對資料。(物件):傳回新的物件。
_.fromPairs([['a', 1], ['b', 2]]);// => { 'a': 1, 'b': 2 }
_.head(array)
取得 array
的第一個元素。
0.1.0
_.first
array
(陣列):要查詢的陣列。(*):傳回 array
的第一個元素。
_.head([1, 2, 3]);// => 1 _.head([]);// => undefined
_.indexOf(array, value, [fromIndex=0])
取得 array
中第一次出現 value
的索引,使用 SameValueZero
進行相等性比較。如果 fromIndex
為負數,則將其用作從 array
結尾的偏移量。
0.1.0
陣列
(陣列):要檢查的陣列。值
(*):要搜尋的值。[fromIndex=0]
(數字):開始搜尋的索引。(數字):傳回配對值的索引,否則傳回 -1
。
_.indexOf([1, 2, 1, 2], 2);// => 1 // Search from the `fromIndex`._.indexOf([1, 2, 1, 2], 2, 2);// => 3
_.initial(陣列)
取得 陣列
中除了最後一個元素之外的所有元素。
0.1.0
array
(陣列):要查詢的陣列。(陣列):傳回 array
的切片。
_.initial([1, 2, 3]);// => [1, 2]
_.intersection([陣列])
使用 SameValueZero
進行相等性比較,建立一個包含所有給定陣列中唯一值的陣列。結果值的順序和參照由第一個陣列決定。
0.1.0
[陣列]
(...陣列):要檢查的陣列。(陣列):傳回相交值的陣列。
_.intersection([2, 1], [2, 3]);// => [2]
_.intersectionBy([陣列], [迭代器=_.identity])
這個方法類似於 _.intersection
,但它接受 迭代器
,會呼叫每個 陣列
的每個元素來產生比較標準。結果值的順序和參照由第一個陣列決定。迭代器會呼叫一個參數
(value).
4.0.0
[陣列]
(...陣列):要檢查的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(陣列):傳回相交值的陣列。
_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);// => [2.1] // The `_.property` iteratee shorthand._.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }]
_.intersectionWith([陣列], [比較器])
此方法類似於 _.intersection
,但它接受用於比較 arrays
元素的 comparator
。結果值的順序和參照由第一個陣列決定。比較器使用兩個參數呼叫:(arrVal, othVal)。
4.0.0
[陣列]
(...陣列):要檢查的陣列。[comparator]
(函式):每個元素呼叫的 comparator。(陣列):傳回相交值的陣列。
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; _.intersectionWith(objects, others, _.isEqual);// => [{ 'x': 1, 'y': 2 }]
_.join(array, [separator=','])
將 array
中的所有元素轉換為以 separator
分隔的字串。
4.0.0
array
(陣列):要轉換的陣列。[separator=',']
(字串):元素分隔符號。(字串):傳回合併的字串。
_.join(['a', 'b', 'c'], '~');// => 'a~b~c'
_.last(array)
取得 array
的最後一個元素。
0.1.0
array
(陣列):要查詢的陣列。(*):傳回 array
的最後一個元素。
_.last([1, 2, 3]);// => 3
_.lastIndexOf(array, value, [fromIndex=array.length-1])
此方法類似於 _.indexOf
,但它從右到左迭代 array
的元素。
0.1.0
陣列
(陣列):要檢查的陣列。值
(*):要搜尋的值。[fromIndex=array.length-1]
(數字):開始搜尋的索引。(數字):傳回配對值的索引,否則傳回 -1
。
_.lastIndexOf([1, 2, 1, 2], 2);// => 3 // Search from the `fromIndex`._.lastIndexOf([1, 2, 1, 2], 2, 2);// => 1
_.nth(array, [n=0])
取得 array
中索引為 n
的元素。如果 n
為負數,則會傳回從結尾開始數起的第 n
個元素。
4.11.0
array
(陣列):要查詢的陣列。[n=0]
(數字): 要傳回的元素索引。(*): 傳回 array
中的第 n
個元素。
var array = ['a', 'b', 'c', 'd']; _.nth(array, 1);// => 'b' _.nth(array, -2);// => 'c';
_.pull(array, [values])
使用 SameValueZero
進行相等比較,從 array
中移除所有指定的數值。
注意:與 _.without
不同,此方法會變更 array
。請使用 _.remove
根據謂詞從陣列中移除元素。
2.0.0
array
(陣列): 要修改的陣列。[values]
(...*): 要移除的數值。(陣列):傳回 array
。
var array = ['a', 'b', 'c', 'a', 'b', 'c']; _.pull(array, 'a', 'c');console.log(array);// => ['b', 'b']
_.pullAll(array, values)
此方法類似於 _.pull
,但它接受一個要移除數值的陣列。
注意:與 _.difference
不同,此方法會變更 array
。
4.0.0
array
(陣列): 要修改的陣列。values
(陣列): 要移除的數值。(陣列):傳回 array
。
var array = ['a', 'b', 'c', 'a', 'b', 'c']; _.pullAll(array, ['a', 'c']);console.log(array);// => ['b', 'b']
_.pullAllBy(array, values, [iteratee=_.identity])
此方法類似於 _.pullAll
,但它接受 `iteratee`,會針對 `array` 和 `values` 的每個元素呼叫它,以產生用於比較它們的準則。iteratee 會使用一個參數呼叫:(value)。
注意:與 _.differenceBy
不同,此方法會變更 `array`。
4.0.0
array
(陣列): 要修改的陣列。values
(陣列): 要移除的數值。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(陣列):傳回 array
。
var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');console.log(array);// => [{ 'x': 2 }]
_.pullAllWith(array, values, [comparator])
此方法類似於 _.pullAll
,但它接受 `comparator`,會呼叫它來比較 `array` 和 `values` 的元素。comparator 會使用兩個參數呼叫:(arrVal, othVal)。
注意:與 _.differenceWith
不同,此方法會變更 `array`。
4.6.0
array
(陣列): 要修改的陣列。values
(陣列): 要移除的數值。[comparator]
(函式):每個元素呼叫的 comparator。(陣列):傳回 array
。
var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);console.log(array);// => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
_.pullAt(array, [indexes])
從 `array` 中移除對應於 `indexes` 的元素,並傳回一個已移除元素的陣列。
注意:與 _.at
不同,此方法會變更 `array`。
3.0.0
array
(陣列): 要修改的陣列。[indexes]
(...(number|number[])):要移除元素的索引。(陣列):傳回已移除元素的新陣列。
var array = ['a', 'b', 'c', 'd'];var pulled = _.pullAt(array, [1, 3]); console.log(array);// => ['a', 'c'] console.log(pulled);// => ['b', 'd']
_.remove(array, [predicate=_.identity])
從 array
中移除所有 predicate
傳回真值的元素,並傳回已移除元素的陣列。此謂詞會使用三個參數呼叫:(value, index, array)。
注意:與 _.filter
不同,此方法會變更 array
。請使用 _.pull
根據值從陣列中移除元素。
2.0.0
array
(陣列): 要修改的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回已移除元素的新陣列。
var array = [1, 2, 3, 4];var evens = _.remove(array, function(n) { return n % 2 == 0;}); console.log(array);// => [1, 3] console.log(evens);// => [2, 4]
_.reverse(array)
反轉 array
,使第一個元素變成最後一個,第二個元素變成倒數第二個,以此類推。
注意:此方法會變更 array
,且基於 Array#reverse
。
4.0.0
array
(陣列): 要修改的陣列。(陣列):傳回 array
。
var array = [1, 2, 3]; _.reverse(array);// => [3, 2, 1] console.log(array);// => [3, 2, 1]
_.slice(array, [start=0], [end=array.length])
建立 array
從 start
到 end
(不包含 end
)的切片。
注意:此方法用於取代 Array#slice
,以確保傳回密集陣列。
3.0.0
array
(陣列):要切片的陣列。[start=0]
(數字):開始位置。[end=array.length]
(數字):結束位置。(陣列):傳回 array
的切片。
_.sortedIndex(array, value)
使用二元搜尋來決定應將 value
插入 array
的最低索引,以維持其排序順序。
0.1.0
array
(陣列): 要檢查的已排序陣列。value
(*): 要評估的值。(數字): 傳回應將 value
插入 array
的索引。
_.sortedIndex([30, 50], 40);// => 1
_.sortedIndexBy(array, value, [iteratee=_.identity])
此方法類似於 _.sortedIndex
,但它接受 iteratee
,會針對 value
和 array
的每個元素呼叫此函式來計算其排序排名。呼叫 iteratee 時只會傳入一個參數:(value)。
4.0.0
array
(陣列): 要檢查的已排序陣列。value
(*): 要評估的值。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(數字): 傳回應將 value
插入 array
的索引。
var objects = [{ 'x': 4 }, { 'x': 5 }]; _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });// => 0 // The `_.property` iteratee shorthand._.sortedIndexBy(objects, { 'x': 4 }, 'x');// => 0
_.sortedIndexOf(array, value)
此方法類似於 _.indexOf
,但它會對已排序的 array
執行二元搜尋。
4.0.0
陣列
(陣列):要檢查的陣列。值
(*):要搜尋的值。(數字):傳回配對值的索引,否則傳回 -1
。
_.sortedIndexOf([4, 5, 5, 5, 6], 5);// => 1
_.sortedLastIndex(array, value)
此方法類似於 _.sortedIndex
,但它會傳回在 `array` 中插入 `value` 以維持其排序順序時應使用的最高索引。
3.0.0
array
(陣列): 要檢查的已排序陣列。value
(*): 要評估的值。(數字): 傳回應將 value
插入 array
的索引。
_.sortedLastIndex([4, 5, 5, 5, 6], 5);// => 4
_.sortedLastIndexBy(array, value, [iteratee=_.identity])
此方法類似於 _.sortedLastIndex
,但它會接受 `iteratee`,而 `iteratee` 會針對 `value` 和 `array` 的每個元素呼叫,以計算其排序排名。`iteratee` 會使用一個引數呼叫:(value)。
4.0.0
array
(陣列): 要檢查的已排序陣列。value
(*): 要評估的值。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(數字): 傳回應將 value
插入 array
的索引。
var objects = [{ 'x': 4 }, { 'x': 5 }]; _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });// => 1 // The `_.property` iteratee shorthand._.sortedLastIndexBy(objects, { 'x': 4 }, 'x');// => 1
_.sortedLastIndexOf(array, value)
此方法類似於 _.lastIndexOf
,但它會對已排序的 `array` 執行二元搜尋。
4.0.0
陣列
(陣列):要檢查的陣列。值
(*):要搜尋的值。(數字):傳回配對值的索引,否則傳回 -1
。
_.sortedLastIndexOf([4, 5, 5, 5, 6], 5);// => 3
_.sortedUniq(array)
此方法類似於 _.uniq
,但它專門設計並最佳化用於已排序的陣列。
4.0.0
陣列
(陣列):要檢查的陣列。(陣列):傳回新的不重複陣列。
_.sortedUniq([1, 1, 2]);// => [1, 2]
_.sortedUniqBy(array, [iteratee])
此方法類似於 _.uniqBy
,但針對已排序陣列進行設計和最佳化。
4.0.0
陣列
(陣列):要檢查的陣列。[iteratee]
(函式): 依序呼叫每個元素的迭代函式。(陣列):傳回新的不重複陣列。
_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);// => [1.1, 2.3]
_.tail(array)
取得 array
中除了第一個元素以外的所有元素。
4.0.0
array
(陣列):要查詢的陣列。(陣列):傳回 array
的切片。
_.tail([1, 2, 3]);// => [2, 3]
_.take(array, [n=1])
建立一個 array
切片,其中包含從開頭取出的 n
個元素。
0.1.0
array
(陣列):要查詢的陣列。[n=1]
(數字): 要取出的元素數量。(陣列):傳回 array
的切片。
_.take([1, 2, 3]);// => [1] _.take([1, 2, 3], 2);// => [1, 2] _.take([1, 2, 3], 5);// => [1, 2, 3] _.take([1, 2, 3], 0);// => []
_.takeRight(array, [n=1])
建立一個 array
切片,其中包含從結尾取出的 n
個元素。
3.0.0
array
(陣列):要查詢的陣列。[n=1]
(數字): 要取出的元素數量。(陣列):傳回 array
的切片。
_.takeRight([1, 2, 3]);// => [3] _.takeRight([1, 2, 3], 2);// => [2, 3] _.takeRight([1, 2, 3], 5);// => [1, 2, 3] _.takeRight([1, 2, 3], 0);// => []
_.takeRightWhile(array, [predicate=_.identity])
建立一個 array
切片,其中包含從結尾取出的元素。元素會持續取出,直到 predicate
傳回假值為止。此謂詞會呼叫三個參數:(value, index, array)。
3.0.0
array
(陣列):要查詢的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回 array
的切片。
var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; _.takeRightWhile(users, function(o) { return !o.active; });// => objects for ['fred', 'pebbles'] // The `_.matches` iteratee shorthand._.takeRightWhile(users, { 'user': 'pebbles', 'active': false });// => objects for ['pebbles'] // The `_.matchesProperty` iteratee shorthand._.takeRightWhile(users, ['active', false]);// => objects for ['fred', 'pebbles'] // The `_.property` iteratee shorthand._.takeRightWhile(users, 'active');// => []
_.takeWhile(array, [predicate=_.identity])
建立一個 array
的切片,包含從開頭取出的元素。元素會持續取出,直到 predicate
傳回假值為止。此謂詞會使用三個參數呼叫:(value, index, array)。
3.0.0
array
(陣列):要查詢的陣列。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回 array
的切片。
var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true }]; _.takeWhile(users, function(o) { return !o.active; });// => objects for ['barney', 'fred'] // The `_.matches` iteratee shorthand._.takeWhile(users, { 'user': 'barney', 'active': false });// => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand._.takeWhile(users, ['active', false]);// => objects for ['barney', 'fred'] // The `_.property` iteratee shorthand._.takeWhile(users, 'active');// => []
_.union([arrays])
建立一個由所有給定陣列中唯一值的順序陣列,使用 SameValueZero
進行相等性比較。
0.1.0
[陣列]
(...陣列):要檢查的陣列。(Array):傳回已結合值的陣列。
_.union([2], [1, 2]);// => [2, 1]
_.unionBy([arrays], [iteratee=_.identity])
此方法類似於 _.union
,但它接受 iteratee
,會針對每個 arrays
的元素呼叫此函式,以產生用於計算唯一性的準則。結果值會從值出現的第一個陣列中選取。此謂詞會使用一個參數呼叫
(value).
4.0.0
[陣列]
(...陣列):要檢查的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(Array):傳回已結合值的陣列。
_.unionBy([2.1], [1.2, 2.3], Math.floor);// => [2.1, 1.2] // The `_.property` iteratee shorthand._.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }, { 'x': 2 }]
_.unionWith([arrays], [comparator])
此方法類似於 _.union
,但它接受 comparator
,會呼叫此函式來比較 arrays
的元素。結果值會從值出現的第一個陣列中選取。此比較器會使用兩個參數呼叫:(arrVal, othVal)。
4.0.0
[陣列]
(...陣列):要檢查的陣列。[comparator]
(函式):每個元素呼叫的 comparator。(Array):傳回已結合值的陣列。
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; _.unionWith(objects, others, _.isEqual);// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
_.uniq(array)
建立一個陣列的重複值移除版本,使用 SameValueZero
進行相等性比較,其中只保留每個元素的第一個出現。結果值的順序由它們在陣列中出現的順序決定。
0.1.0
陣列
(陣列):要檢查的陣列。(陣列):傳回新的不重複陣列。
_.uniq([2, 1, 2]);// => [2, 1]
_.uniqBy(array, [iteratee=_.identity])
此方法類似於 _.uniq
,但它接受 iteratee
,該 iteratee
會對 array
中的每個元素呼叫,以產生計算唯一性的準則。結果值的順序由它們在陣列中出現的順序決定。iteratee 會使用一個引數呼叫
(value).
4.0.0
陣列
(陣列):要檢查的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(陣列):傳回新的不重複陣列。
_.uniqBy([2.1, 1.2, 2.3], Math.floor);// => [2.1, 1.2] // The `_.property` iteratee shorthand._.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }, { 'x': 2 }]
_.uniqWith(array, [comparator])
此方法類似於 _.uniq
,但它接受 comparator
,該 comparator
會呼叫來比較 array
的元素。結果值的順序由它們在陣列中出現的順序決定。比較器會使用兩個引數呼叫:(arrVal, othVal)。
4.0.0
陣列
(陣列):要檢查的陣列。[comparator]
(函式):每個元素呼叫的 comparator。(陣列):傳回新的不重複陣列。
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; _.uniqWith(objects, _.isEqual);// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
_.unzip(array)
此方法類似於 _.zip
,但它接受群組元素的陣列,並建立一個將元素重新群組為其壓縮前設定的陣列。
1.2.0
array
(陣列):要處理的群組元素陣列。(陣列):傳回重新群組元素的新陣列。
var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);// => [['a', 1, true], ['b', 2, false]] _.unzip(zipped);// => [['a', 'b'], [1, 2], [true, false]]
_.unzipWith(array, [iteratee=_.identity])
此方法類似於 _.unzip
,但它接受 iteratee
來指定應如何合併重新群組的值。iteratee 會呼叫每個群組的元素:(...group)。
3.8.0
array
(陣列):要處理的群組元素陣列。[iteratee=_.identity]
(函式):用來合併重新群組值的函式。(陣列):傳回重新群組元素的新陣列。
var zipped = _.zip([1, 2], [10, 20], [100, 200]);// => [[1, 10, 100], [2, 20, 200]] _.unzipWith(zipped, _.add);// => [3, 30, 300]
_.without(array, [values])
使用 SameValueZero
進行相等比較,建立一個排除所有給定值的陣列。
注意:與 _.pull
不同,此方法會傳回一個新陣列。
0.1.0
陣列
(陣列):要檢查的陣列。[values]
(...*):要排除的值。(陣列): 傳回過濾後的新陣列。
_.without([2, 1, 2, 3], 1, 2);// => [3]
_.xor([arrays])
建立一個唯一值的陣列,這是給定陣列的對稱差集。結果值順序由它們在陣列中出現的順序決定。
2.4.0
[陣列]
(...陣列):要檢查的陣列。(陣列): 傳回過濾後的新陣列。
_.xor([2, 1], [2, 3]);// => [1, 3]
_.xorBy([arrays], [iteratee=_.identity])
此方法類似於 _.xor
,但它接受 `iteratee`,它會針對每個 `arrays` 的每個元素呼叫,以產生用於比較它們的準則。結果值順序由它們在陣列中出現的順序決定。iteratee 會使用一個參數呼叫:(value)。
4.0.0
[陣列]
(...陣列):要檢查的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(陣列): 傳回過濾後的新陣列。
_.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);// => [1.2, 3.4] // The `_.property` iteratee shorthand._.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 2 }]
_.xorWith([arrays], [comparator])
此方法類似於 _.xor
,但它接受 `comparator`,它會呼叫來比較 `arrays` 的元素。結果值順序由它們在陣列中出現的順序決定。comparator 會使用兩個參數呼叫:(arrVal, othVal)。
4.0.0
[陣列]
(...陣列):要檢查的陣列。[comparator]
(函式):每個元素呼叫的 comparator。(陣列): 傳回過濾後的新陣列。
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; _.xorWith(objects, others, _.isEqual);// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
_.zip([arrays])
建立一個群組元素的陣列,第一個包含給定陣列的第一個元素,第二個包含給定陣列的第二個元素,以此類推。
0.1.0
[arrays]
(...Array):要處理的陣列。(Array):傳回群組元素的新陣列。
_.zip(['a', 'b'], [1, 2], [true, false]);// => [['a', 1, true], ['b', 2, false]]
_.zipObject([props=[]], [values=[]])
此方法類似於 _.fromPairs
,但它接受兩個陣列,一個是屬性識別碼,另一個是對應的值。
0.4.0
[props=[]]
(陣列): 屬性識別碼。[values=[]]
(陣列): 屬性值。(物件):傳回新的物件。
_.zipObject(['a', 'b'], [1, 2]);// => { 'a': 1, 'b': 2 }
_.zipObjectDeep([props=[]], [values=[]])
此方法類似於 _.zipObject
,但它支援屬性路徑。
4.1.0
[props=[]]
(陣列): 屬性識別碼。[values=[]]
(陣列): 屬性值。(物件):傳回新的物件。
_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
_.zipWith([arrays], [iteratee=_.identity])
此方法類似於 _.zip
,但它接受 iteratee
來指定如何合併分組值。iteratee 會呼叫每個分組的元素:(...group)。
3.8.0
[arrays]
(...Array):要處理的陣列。[iteratee=_.identity]
(函式): 合併分組值的函式。(Array):傳回群組元素的新陣列。
_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { return a + b + c;});// => [111, 222]
「集合」方法
_.countBy(collection, [iteratee=_.identity])
建立一個物件,其金鑰是由執行 collection
中每個元素的 iteratee
結果產生的。每個金鑰的對應值是 iteratee
傳回金鑰的次數。iteratee 會呼叫一個引數:(value)。
0.5.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):轉換金鑰的迭代器。(物件):傳回組成的聚合物件。
_.countBy([6.1, 4.2, 6.3], Math.floor);// => { '4': 1, '6': 2 } // The `_.property` iteratee shorthand._.countBy(['one', 'two', 'three'], 'length');// => { '3': 2, '5': 1 }
_.every(collection, [predicate=_.identity])
檢查 predicate
是否對 collection
的所有元素傳回真值。一旦 predicate
傳回假值,就會停止迭代。此謂詞會以三個參數呼叫:(value, index|key, collection)。
注意:此方法會對空集合傳回 true
,因為空集合的元素一切都為真。
0.1.0
collection
(陣列|物件):要迭代的集合。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(布林值):如果所有元素都通過謂詞檢查,則傳回 true
,否則傳回 false
。
_.every([true, 1, null, 'yes'], Boolean);// => false var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': false }]; // The `_.matches` iteratee shorthand._.every(users, { 'user': 'barney', 'active': false });// => false // The `_.matchesProperty` iteratee shorthand._.every(users, ['active', false]);// => true // The `_.property` iteratee shorthand._.every(users, 'active');// => false
_.filter(collection, [predicate=_.identity])
迭代 collection
的元素,傳回一個陣列,其中包含 predicate
傳回真值的元素。此謂詞會以三個參數呼叫:(value, index|key, collection)。
注意:與 _.remove
不同,此方法會傳回一個新的陣列。
0.1.0
collection
(陣列|物件):要迭代的集合。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回新的過濾陣列。
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; _.filter(users, function(o) { return !o.active; });// => objects for ['fred'] // The `_.matches` iteratee shorthand._.filter(users, { 'age': 36, 'active': true });// => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand._.filter(users, ['active', false]);// => objects for ['fred'] // The `_.property` iteratee shorthand._.filter(users, 'active');// => objects for ['barney']
_.find(collection, [predicate=_.identity], [fromIndex=0])
遍歷 collection
的元素,傳回第一個 predicate
傳回真值的元素。此謂詞會使用三個參數呼叫:(值、索引或金鑰、collection)。
0.1.0
collection
(陣列或物件):要檢查的 collection。[predicate=_.identity]
(函式):每個反覆呼叫的函式。[fromIndex=0]
(數字):開始搜尋的索引。(*):傳回配對的元素,否則傳回 undefined
。
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; });// => object for 'barney' // The `_.matches` iteratee shorthand._.find(users, { 'age': 1, 'active': true });// => object for 'pebbles' // The `_.matchesProperty` iteratee shorthand._.find(users, ['active', false]);// => object for 'fred' // The `_.property` iteratee shorthand._.find(users, 'active');// => object for 'barney'
_.findLast(collection, [predicate=_.identity], [fromIndex=collection.length-1])
此方法類似 _.find
,但會從右到左遍歷 collection
的元素。
2.0.0
collection
(陣列或物件):要檢查的 collection。[predicate=_.identity]
(函式):每個反覆呼叫的函式。[fromIndex=collection.length-1]
(數字):要開始搜尋的索引。(*):傳回配對的元素,否則傳回 undefined
。
_.findLast([1, 2, 3, 4], function(n) { return n % 2 == 1;});// => 3
_.flatMap(collection, [iteratee=_.identity])
透過對 collection
中的每個元素執行 iteratee
,並壓平對應的結果,建立一個壓平的陣列。此謂詞會使用三個參數呼叫:(值、索引或金鑰、collection)。
4.0.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(陣列):傳回新的扁平陣列。
function duplicate(n) { return [n, n];} _.flatMap([1, 2], duplicate);// => [1, 1, 2, 2]
_.flatMapDeep(collection, [iteratee=_.identity])
此方法類似於 _.flatMap
,但會遞迴扁平化對應的結果。
4.7.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(陣列):傳回新的扁平陣列。
function duplicate(n) { return [[[n, n]]];} _.flatMapDeep([1, 2], duplicate);// => [1, 1, 2, 2]
_.flatMapDepth(collection, [iteratee=_.identity], [depth=1])
此方法類似於 _.flatMap
,但會遞迴扁平化對應的結果,最多到 depth
次。
4.7.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。[depth=1]
(數字):最大遞迴深度。(陣列):傳回新的扁平陣列。
function duplicate(n) { return [[[n, n]]];} _.flatMapDepth([1, 2], duplicate, 2);// => [[1, 1], [2, 2]]
_.forEach(collection, [iteratee=_.identity])
遍歷 collection
的元素,並對每個元素呼叫 iteratee
。iteratee 會呼叫三個參數:(value, index|key, collection)。iteratee 函式可以透過明確傳回 false
來提早結束遍歷。
注意:與其他「集合」方法一樣,具有「length」屬性的物件會像陣列一樣遍歷。若要避免這種行為,請使用 _.forIn
或 _.forOwn
來遍歷物件。
0.1.0
_.each
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(*):傳回 collection
。
_.forEach([1, 2], function(value) { console.log(value);});// => Logs `1` then `2`. _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { console.log(key);});// => Logs 'a' then 'b' (iteration order is not guaranteed).
_.forEachRight(collection, [iteratee=_.identity])
這個方法類似 _.forEach
,但會從右到左遍歷 `collection` 的元素。
2.0.0
_.eachRight
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(*):傳回 collection
。
_.forEachRight([1, 2], function(value) { console.log(value);});// => Logs `2` then `1`.
_.groupBy(collection, [iteratee=_.identity])
建立一個物件,其金鑰是由執行 `collection` 中每個元素的 `iteratee` 結果產生的。已分組值的順序由它們在 `collection` 中出現的順序決定。每個金鑰對應的值是一個負責產生該金鑰的元素陣列。iteratee 會呼叫一個參數:(value)。
0.1.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):轉換金鑰的迭代器。(物件):傳回組成的聚合物件。
_.groupBy([6.1, 4.2, 6.3], Math.floor);// => { '4': [4.2], '6': [6.1, 6.3] } // The `_.property` iteratee shorthand._.groupBy(['one', 'two', 'three'], 'length');// => { '3': ['one', 'two'], '5': ['three'] }
_.includes(collection, value, [fromIndex=0])
檢查 `value` 是否在 `collection` 中。如果 `collection` 是字串,會檢查 `value` 是否是其子字串,否則會使用 SameValueZero
進行相等比較。如果 `fromIndex` 為負值,會用作從 `collection` 結尾的偏移量。
0.1.0
collection
(Array|Object|string):要檢查的集合。值
(*):要搜尋的值。[fromIndex=0]
(數字):開始搜尋的索引。(布林值):如果找到 value
,則傳回 true
,否則傳回 false
。
_.includes([1, 2, 3], 1);// => true _.includes([1, 2, 3], 1, 2);// => false _.includes({ 'a': 1, 'b': 2 }, 1);// => true _.includes('abcd', 'bc');// => true
_.invokeMap(collection, path, [args])
呼叫 collection
中每個元素的 path
方法,傳回呼叫每個方法的結果陣列。任何其他引數都會提供給每個呼叫的方法。如果 path
是函式,則會針對 collection
中的每個元素呼叫該函式,並將 this
繫結到該元素。
4.0.0
collection
(陣列|物件):要迭代的集合。path
(陣列|函式|字串):要呼叫的方法路徑,或每個反覆運算呼叫的函式。[args]
(...*):呼叫每個方法的引數。(陣列):傳回結果陣列。
_.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');// => [[1, 5, 7], [1, 2, 3]] _.invokeMap([123, 456], String.prototype.split, '');// => [['1', '2', '3'], ['4', '5', '6']]
_.keyBy(collection, [iteratee=_.identity])
建立一個物件,其金鑰是由執行 collection
中每個元素的 iteratee
結果產生的。每個金鑰對應的值是產生該金鑰的最後一個元素。iteratee 會呼叫一個引數:(value)。
4.0.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):轉換金鑰的迭代器。(物件):傳回組成的聚合物件。
var array = [ { 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }]; _.keyBy(array, function(o) { return String.fromCharCode(o.code);});// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } _.keyBy(array, 'dir');// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
_.map(collection, [iteratee=_.identity])
建立一個值陣列,方法是執行 collection
中的每個元素的 iteratee
。iteratee 會呼叫三個引數
(值, 索引|金鑰, 集合).
許多 lodash 方法受到保護,可作為 _.every
、_.filter
、_.map
、_.mapValues
、_.reject
和 _.some
等方法的迭代函數。
受到保護的方法為ary
、chunk
、curry
、curryRight
、drop
、dropRight
、every
、fill
、invert
、parseInt
、random
、range
、rangeRight
、repeat
、sampleSize
、slice
、some
、sortBy
、split
、take
、takeRight
、template
、trim
、trimEnd
、trimStart
和 words
0.1.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(陣列):傳回新的對應陣列。
function square(n) { return n * n;} _.map([4, 8], square);// => [16, 64] _.map({ 'a': 4, 'b': 8 }, square);// => [16, 64] (iteration order is not guaranteed) var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; // The `_.property` iteratee shorthand._.map(users, 'user');// => ['barney', 'fred']
_.orderBy(collection, [iteratees=[_.identity]], [orders])
此方法類似於 _.sortBy
,但允許指定用於排序的迭代函數的排序順序。如果未指定 orders
,所有值都按遞增順序排序。否則,請指定「desc」順序,表示對應值的遞減排序,或指定「asc」順序,表示對應值的遞增排序。
4.0.0
collection
(陣列|物件):要迭代的集合。[iteratees=[_.identity]]
(Array[]|Function[]|Object[]|string[]):用於排序的迭代函數。[orders]
(字串陣列):iteratees
的排序順序。(陣列):傳回新的已排序陣列。
var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 34 }, { 'user': 'fred', 'age': 40 }, { 'user': 'barney', 'age': 36 }]; // Sort by `user` in ascending order and by `age` in descending order._.orderBy(users, ['user', 'age'], ['asc', 'desc']);// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
_.partition(collection, [predicate=_.identity])
建立一個元素陣列,分成兩組,第一組包含 predicate
傳回真值的元素,第二組包含 predicate
傳回假值的元素。此謂詞會呼叫一個參數:(value)。
3.0.0
collection
(陣列|物件):要迭代的集合。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回已分組元素的陣列。
var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': true }, { 'user': 'pebbles', 'age': 1, 'active': false }]; _.partition(users, function(o) { return o.active; });// => objects for [['fred'], ['barney', 'pebbles']] // The `_.matches` iteratee shorthand._.partition(users, { 'age': 1, 'active': false });// => objects for [['pebbles'], ['barney', 'fred']] // The `_.matchesProperty` iteratee shorthand._.partition(users, ['active', false]);// => objects for [['barney', 'pebbles'], ['fred']] // The `_.property` iteratee shorthand._.partition(users, 'active');// => objects for [['fred'], ['barney', 'pebbles']]
_.reduce(collection, [iteratee=_.identity], [accumulator])
將 collection
縮減為一個值,此值是執行 collection
中每個元素透過 iteratee
的累積結果,其中每個後續呼叫都會提供前一個的傳回值。如果未提供 accumulator
,則 collection
的第一個元素會用作初始值。呼叫 iteratee 時會提供四個參數
(accumulator, value, index|key, collection).
許多 lodash 方法都受到保護,可用作 _.reduce
、_.reduceRight
和 _.transform
等方法的 iteratee。
受到保護的方法為assign
、defaults
、defaultsDeep
、includes
、merge
、orderBy
和 sortBy
0.1.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。[accumulator]
(*):初始值。(*):傳回累積值。
_.reduce([1, 2], function(sum, n) { return sum + n;}, 0);// => 3 _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { (result[value] || (result[value] = [])).push(key); return result;}, {});// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
_.reduceRight(collection, [iteratee=_.identity], [accumulator])
此方法類似於 _.reduce
,但從右到左迭代 collection
的元素。
0.1.0
collection
(陣列|物件):要迭代的集合。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。[accumulator]
(*):初始值。(*):傳回累積值。
var array = [[0, 1], [2, 3], [4, 5]]; _.reduceRight(array, function(flattened, other) { return flattened.concat(other);}, []);// => [4, 5, 2, 3, 0, 1]
_.reject(collection, [predicate=_.identity])
與 _.filter
相反;此方法傳回 collection
中 predicate
不傳回真值的元素。
0.1.0
collection
(陣列|物件):要迭代的集合。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(陣列):傳回新的過濾陣列。
var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': true }]; _.reject(users, function(o) { return !o.active; });// => objects for ['fred'] // The `_.matches` iteratee shorthand._.reject(users, { 'age': 40, 'active': true });// => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand._.reject(users, ['active', false]);// => objects for ['fred'] // The `_.property` iteratee shorthand._.reject(users, 'active');// => objects for ['barney']
_.sample(collection)
從 collection
中取得一個隨機元素。
2.0.0
collection
(Array|Object):要取樣的集合。(*):傳回隨機元素。
_.sample([1, 2, 3, 4]);// => 2
_.sampleSize(collection, [n=1])
從 collection
中取得 n
個隨機元素,其鍵值唯一,最多到 collection
的大小。
4.0.0
collection
(Array|Object):要取樣的集合。[n=1]
(number):要取樣的元素數量。(Array):傳回隨機元素。
_.sampleSize([1, 2, 3], 2);// => [3, 1] _.sampleSize([1, 2, 3], 4);// => [2, 3, 1]
_.shuffle(collection)
使用 費雪-耶茲洗牌法 的版本,建立一個洗牌後的數值陣列。
0.1.0
collection
(陣列|物件): 要洗牌的集合。(陣列): 傳回新的洗牌陣列。
_.shuffle([1, 2, 3, 4]);// => [4, 1, 3, 2]
_.size(collection)
取得 collection
的大小,對於類陣列的值傳回其長度,或對於物件傳回可列舉的字串鍵值屬性的數量。
0.1.0
collection
(Array|Object|string):要檢查的集合。(數字): 傳回集合的大小。
_.size([1, 2, 3]);// => 3 _.size({ 'a': 1, 'b': 2 });// => 2 _.size('pebbles');// => 7
_.some(collection, [predicate=_.identity])
檢查 predicate
是否對 collection
的任何元素傳回真值。一旦 predicate
傳回真值,就會停止反覆運算。此謂詞會以三個參數呼叫:(value, index|key, collection)。
0.1.0
collection
(陣列|物件):要迭代的集合。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(布林值): 如果任何元素通過謂詞檢查,則傳回 true
,否則傳回 false
。
_.some([null, 0, 'yes', false], Boolean);// => true var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }]; // The `_.matches` iteratee shorthand._.some(users, { 'user': 'barney', 'active': false });// => false // The `_.matchesProperty` iteratee shorthand._.some(users, ['active', false]);// => true // The `_.property` iteratee shorthand._.some(users, 'active');// => true
_.sortBy(collection, [iteratees=[_.identity]])
建立一個陣列,依據執行每個集合元素的每個迭代函式結果,以遞增順序排序。此方法執行穩定排序,也就是說,它會保留相等元素的原始排序順序。迭代函式會呼叫一個參數:(值)。
0.1.0
collection
(陣列|物件):要迭代的集合。[iteratees=[_.identity]]
(...(Function|Function[])):用來排序的迭代函式。(陣列):傳回新的已排序陣列。
var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'barney', 'age': 34 }]; _.sortBy(users, [function(o) { return o.user; }]);// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] _.sortBy(users, ['user', 'age']);// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
「日期」方法
「函式」方法
_.after(n, func)
_.before
的反向操作;此方法會建立一個函式,在被呼叫 n
次或更多次後,才會呼叫 func
。
0.1.0
n
(數字):呼叫 func
之前的呼叫次數。func
(函式):要限制的函式。(函式):傳回新的受限制函式。
var saves = ['profile', 'settings']; var done = _.after(saves.length, function() { console.log('done saving!');}); _.forEach(saves, function(type) { asyncSave({ 'type': type, 'complete': done });});// => Logs 'done saving!' after the two async saves have completed.
_.ary(func, [n=func.length])
建立一個函式,呼叫 func
,最多有 n
個參數,忽略任何其他參數。
3.0.0
func
(函式): 要限制參數的函式。[n=func.length]
(數字): 參數上限。(函式): 傳回新的限制函式。
_.map(['6', '8', '10'], _.ary(parseInt, 1));// => [6, 8, 10]
_.before(n, func)
建立一個函式,呼叫 func
,使用建立函式的 this
繫結和參數,同時呼叫次數少於 n
次。後續呼叫建立的函式會傳回最後一次 func
呼叫的結果。
3.0.0
n
(數字): 不再呼叫 func
的呼叫次數。func
(函式):要限制的函式。(函式):傳回新的受限制函式。
jQuery(element).on('click', _.before(5, addContactToList));// => Allows adding up to 4 contacts to the list.
_.bind(func, thisArg, [partials])
建立一個函式,呼叫 func
,使用 thisArg
的 this
繫結,並將 partials
預先加到它接收到的參數。_.bind.placeholder
值,在單一建置中預設為 _
,可用作部分套用參數的佔位符。
注意:與原生 Function#bind
不同,此方法不會設定繫結函式的「長度」屬性。
0.1.0
func
(函數):要綁定的函數。thisArg
(*):func
的 this
繫結。[partials]
(...*):要部分套用的參數。(函數):傳回新的繫結函數。
function greet(greeting, punctuation) { return greeting + ' ' + this.user + punctuation;} var object = { 'user': 'fred' }; var bound = _.bind(greet, object, 'hi');bound('!');// => 'hi fred!' // Bound with placeholders.var bound = _.bind(greet, object, _, '!');bound('hi');// => 'hi fred!'
_.bindKey(object, key, [partials])
建立一個函數,它會呼叫 object[key]
的方法,並將 partials
預先加入它所接收的參數中。
此方法與 _.bind
的不同之處,在於它允許繫結函數參照可能會重新定義或尚未存在的方法。請參閱 Peter Michaux 的文章 以取得更多詳細資料。_.bindKey.placeholder
值,在單體建置中預設為 _
,可以用作部分套用參數的佔位符。
0.10.0
object
(物件):要呼叫方法的物件。key
(字串):方法的鍵。[partials]
(...*):要部分套用的參數。(函數):傳回新的繫結函數。
var object = { 'user': 'fred', 'greet': function(greeting, punctuation) { return greeting + ' ' + this.user + punctuation; }}; var bound = _.bindKey(object, 'greet', 'hi');bound('!');// => 'hi fred!' object.greet = function(greeting, punctuation) { return greeting + 'ya ' + this.user + punctuation;}; bound('!');// => 'hiya fred!' // Bound with placeholders.var bound = _.bindKey(object, 'greet', _, '!');bound('hi');// => 'hiya fred!'
_.curry(func, [arity=func.length])
建立一個函數,它接受 func
的參數,並呼叫 func
傳回其結果,如果已提供至少 arity
個參數,或傳回一個函數,它接受 func
的剩餘參數,依此類推。如果 func.length
不足夠,則可以指定 func
的 arity。_.curry.placeholder
值,在單一建置中預設為 _
,可用作已提供引數的佔位符。
注意:此方法不會設定已封裝函式的「長度」屬性。
2.0.0
func
(函式):要封裝的函式。[arity=func.length]
(數字):func
的 arity。(函式):傳回新的已封裝函式。
var abc = function(a, b, c) { return [a, b, c];}; var curried = _.curry(abc); curried(1)(2)(3);// => [1, 2, 3] curried(1, 2)(3);// => [1, 2, 3] curried(1, 2, 3);// => [1, 2, 3] // Curried with placeholders.curried(1)(_, 3)(2);// => [1, 3, 2]
_.curryRight(func, [arity=func.length])
此方法類似於 _.curry
,但引數會以 _.partialRight
的方式套用至 func
,而非 _.partial
。_.curryRight.placeholder
值,在單一建置中預設為 _
,可用作已提供引數的佔位符。
注意:此方法不會設定已封裝函式的「長度」屬性。
3.0.0
func
(函式):要封裝的函式。[arity=func.length]
(數字):func
的 arity。(函式):傳回新的已封裝函式。
var abc = function(a, b, c) { return [a, b, c];}; var curried = _.curryRight(abc); curried(3)(2)(1);// => [1, 2, 3] curried(2, 3)(1);// => [1, 2, 3] curried(1, 2, 3);// => [1, 2, 3] // Curried with placeholders.curried(3)(1, _)(2);// => [1, 2, 3]
_.debounce(func, [wait=0], [options={}])
建立一個延遲函式,延遲呼叫 func
,直到距離延遲函式上次呼叫經過 wait
毫秒後。延遲函式附帶一個 cancel
方法,用於取消延遲的 func
呼叫,以及一個 flush
方法,用於立即呼叫它們。提供 options
以指示是否應在 wait
超時時間的開始或結束邊緣呼叫 func
。func
會使用提供給延遲函式的最後一個引數呼叫。延遲函式的後續呼叫會傳回最後一個 func
呼叫的結果。
注意:如果 leading
和 trailing
選項為 true
,則僅當在 wait
超時時間內多次呼叫延遲函式時,才會在超時的結束邊緣呼叫 func
。
如果 wait
為 0
且 leading
為 false
,則會延遲 func
呼叫,直到下一個滴答,類似於超時時間為 0
的 setTimeout
。
請參閱 David Corbacho 的文章,以瞭解 _.debounce
和 _.throttle
之間的差異。
0.1.0
func
(函式):要延遲的函式。[wait=0]
(數字):要延遲的毫秒數。[options={}]
(物件):選項物件。[options.leading=false]
(布林值):指定在超時的開始邊緣呼叫。[options.maxWait]
(數字):允許延遲呼叫 func
的最長時間。[options.trailing=true]
(布林值):指定在逾時結束時呼叫。(函式):傳回新的防彈函式。
// Avoid costly calculations while the window size is in flux.jQuery(window).on('resize', _.debounce(calculateLayout, 150)); // Invoke `sendMail` when clicked, debouncing subsequent calls.jQuery(element).on('click', _.debounce(sendMail, 300, { 'leading': true, 'trailing': false})); // Ensure `batchLog` is invoked once after 1 second of debounced calls.var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });var source = new EventSource('/stream');jQuery(source).on('message', debounced); // Cancel the trailing debounced invocation.jQuery(window).on('popstate', debounced.cancel);
_.defer(func, [args])
延遲呼叫 func
,直到目前呼叫堆疊清除為止。呼叫時會將任何其他引數提供給 func
。
0.1.0
func
(函式):要延遲的函式。[args]
(...*):呼叫 func
時要使用的引數。(數字):傳回計時器 ID。
_.defer(function(text) { console.log(text);}, 'deferred');// => Logs 'deferred' after one millisecond.
_.delay(func, wait, [args])
在 wait
毫秒後呼叫 func
。呼叫時會將任何其他引數提供給 func
。
0.1.0
func
(函式):要延遲的函式。wait
(數字):要延遲呼叫的毫秒數。[args]
(...*):呼叫 func
時要使用的引數。(數字):傳回計時器 ID。
_.delay(function(text) { console.log(text);}, 1000, 'later');// => Logs 'later' after one second.
_.flip(func)
建立一個函式,呼叫 func
時會反轉引數。
4.0.0
func
(函數):要反轉參數的函數。(函數):傳回新的反轉函數。
var flipped = _.flip(function() { return _.toArray(arguments);}); flipped('a', 'b', 'c', 'd');// => ['d', 'c', 'b', 'a']
_.memoize(func, [resolver])
建立一個函數,將 func
的結果記憶化。如果提供了 resolver
,它會根據傳遞給記憶化函數的參數,來決定用於儲存結果的快取金鑰。預設情況下,傳遞給記憶化函數的第一個參數會用作對應快取金鑰。func
會使用記憶化函數的 this
繫結來呼叫。
注意:快取會在記憶化函數上公開為 cache
屬性。它可以透過將 _.memoize.Cache
建構函式替換為實作 clear
、delete
、get
、has
和 set
等 Map
方法介面的實例,來自訂建立方式。
0.1.0
func
(函數):要記憶化其輸出的函數。[resolver]
(函數):用於解析快取金鑰的函數。(函數):傳回新的記憶化函數。
var object = { 'a': 1, 'b': 2 };var other = { 'c': 3, 'd': 4 }; var values = _.memoize(_.values);values(object);// => [1, 2] values(other);// => [3, 4] object.a = 2;values(object);// => [1, 2] // Modify the result cache.values.cache.set(object, ['a', 'b']);values(object);// => ['a', 'b'] // Replace `_.memoize.Cache`._.memoize.Cache = WeakMap;
_.negate(predicate)
建立一個函數,用來否定謂詞 func
的結果。func
謂詞會使用建立函數的 this
繫結和參數來呼叫。
3.0.0
predicate
(函數):要否定的謂詞。(函數):傳回新的否定函數。
function isEven(n) { return n % 2 == 0;} _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));// => [1, 3, 5]
_.once(func)
建立一個函式,限制只能呼叫 func
一次。重複呼叫函式會傳回第一次呼叫的值。func
會以建立函式的 this
繫結和參數來呼叫。
0.1.0
func
(函式):要限制的函式。(函式):傳回新的受限制函式。
var initialize = _.once(createApplication);initialize();initialize();// => `createApplication` is invoked once
_.overArgs(func, [transforms=[_.identity]])
建立一個函式,以轉換後的參數呼叫 func
。
4.0.0
func
(Function): 要包裝的函式。[transforms=[_.identity]]
(...(Function|Function[])): 參數轉換。(Function): 傳回新的函式。
function doubled(n) { return n * 2;} function square(n) { return n * n;} var func = _.overArgs(function(x, y) { return [x, y];}, [square, doubled]); func(9, 3);// => [81, 6] func(10, 5);// => [100, 10]
_.partial(func, [partials])
建立一個函式,以 partials
預先附加到它接收到的參數來呼叫 func
。此方法類似於 _.bind
,但它不會變更 this
繫結。_.partial.placeholder
值,在單體建構中預設為 _
,可用作部分套用引數的佔位符。
注意:此方法不會設定部分套用函式的「長度」屬性。
0.2.0
func
(函式):要將引數部分套用的函式。[partials]
(...*):要部分套用的參數。(函式):傳回新的部分套用函式。
function greet(greeting, name) { return greeting + ' ' + name;} var sayHelloTo = _.partial(greet, 'hello');sayHelloTo('fred');// => 'hello fred' // Partially applied with placeholders.var greetFred = _.partial(greet, _, 'fred');greetFred('hi');// => 'hi fred'
_.partialRight(func, [partials])
此方法類似於 _.partial
,但部分套用的引數會附加到它接收到的引數。_.partialRight.placeholder
值,在單體建構中預設為 _
,可用作部分套用引數的佔位符。
注意:此方法不會設定部分套用函式的「長度」屬性。
1.0.0
func
(函式):要將引數部分套用的函式。[partials]
(...*):要部分套用的參數。(函式):傳回新的部分套用函式。
function greet(greeting, name) { return greeting + ' ' + name;} var greetFred = _.partialRight(greet, 'fred');greetFred('hi');// => 'hi fred' // Partially applied with placeholders.var sayHelloTo = _.partialRight(greet, 'hello', _);sayHelloTo('fred');// => 'hello fred'
_.rearg(func, indexes)
建立一個函式,呼叫 func
時,引數會根據指定的 indexes
排列,其中第一個索引的引數值會提供為第一個引數,第二個索引的引數值會提供為第二個引數,以此類推。
3.0.0
func
(函式):要為其重新排列引數的函式。indexes
(...(數字|數字陣列)):已排列的引數索引。(Function): 傳回新的函式。
var rearged = _.rearg(function(a, b, c) { return [a, b, c];}, [2, 0, 1]); rearged('b', 'c', 'a')// => ['a', 'b', 'c']
_.rest(func, [start=func.length-1])
建立一個函式,呼叫 func
時,會使用建立的函式的 this
繫結,並將從 start
開始的引數提供為陣列。
注意:此方法基於 rest 參數。
4.0.0
func
(函數):要套用 rest 參數的函數。[start=func.length-1]
(數字):rest 參數的開始位置。(Function): 傳回新的函式。
var say = _.rest(function(what, names) { return what + ' ' + _.initial(names).join(', ') + (_.size(names) > 1 ? ', & ' : '') + _.last(names);}); say('hello', 'fred', 'barney', 'pebbles');// => 'hello fred, barney, & pebbles'
_.spread(func, [start=0])
建立一個函數,會使用建立函數的 this
繫結和一個陣列引數來呼叫 func
,非常類似於 Function#apply
。
注意:此方法基於 展開運算子。
3.2.0
func
(函數):要展開引數的函數。[start=0]
(數字):展開的開始位置。(Function): 傳回新的函式。
var say = _.spread(function(who, what) { return who + ' says ' + what;}); say(['fred', 'hello']);// => 'fred says hello' var numbers = Promise.all([ Promise.resolve(40), Promise.resolve(36)]); numbers.then(_.spread(function(x, y) { return x + y;}));// => a Promise of 76
_.throttle(func, [wait=0], [options={}])
建立一個受限函式,每隔 wait
毫秒才會呼叫 func
一次。受限函式會附帶一個 cancel
方法,用於取消延遲的 func
呼叫,以及一個 flush
方法,用於立即呼叫它們。提供 options
以指示 func
是否應在 wait
超時時間的前緣和/或後緣呼叫。func
會呼叫受限函式提供的最後一個參數。後續呼叫受限函式會傳回最後一個 func
呼叫的結果。
注意:如果 leading
和 trailing
選項為 true
,則只有在 wait
超時期間呼叫受限函式多次時,才會在超時的後緣呼叫 func
。
如果 wait
為 0
且 leading
為 false
,則會延遲 func
呼叫,直到下一個滴答,類似於超時時間為 0
的 setTimeout
。
請參閱 David Corbacho 的文章,以了解 _.throttle
和 _.debounce
之間的差異。
0.1.0
func
(函式):要受限的函式。[wait=0]
(數字):要將呼叫受限為多少毫秒的數字。[options={}]
(物件):選項物件。[options.leading=true]
(布林值):指定在超時的前緣呼叫。[options.trailing=true]
(布林值):指定在逾時結束時呼叫。(函式):傳回新的受限函式。
// Avoid excessively updating the position while scrolling.jQuery(window).on('scroll', _.throttle(updatePosition, 100)); // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.var throttled = _.throttle(renewToken, 300000, { 'trailing': false });jQuery(element).on('click', throttled); // Cancel the trailing throttled invocation.jQuery(window).on('popstate', throttled.cancel);
_.unary(func)
建立一個函式,接受最多一個參數,忽略任何額外的參數。
4.0.0
func
(函式): 要限制參數的函式。(函式): 傳回新的限制函式。
_.map(['6', '8', '10'], _.unary(parseInt));// => [6, 8, 10]
_.wrap(value, [wrapper=identity])
建立一個函式,將 value
提供給 wrapper
作為其第一個參數。提供給函式的任何額外參數都會附加到提供給 wrapper
的參數。wrapper 會以建立函式的 this
繫結來呼叫。
0.1.0
value
(*): 要包裝的值。[wrapper=identity]
(Function): wrapper 函式。(Function): 傳回新的函式。
var p = _.wrap(_.escape, function(func, text) { return '<p>' + func(text) + '</p>';}); p('fred, barney, & pebbles');// => '<p>fred, barney, & pebbles</p>'
「Lang」方法
_.castArray(value)
如果 value
不是陣列,則將其轉換為陣列。
4.4.0
value
(*): 要檢查的值。(Array): 傳回轉換後的陣列。
_.castArray(1);// => [1] _.castArray({ 'a': 1 });// => [{ 'a': 1 }] _.castArray('abc');// => ['abc'] _.castArray(null);// => [null] _.castArray(undefined);// => [undefined] _.castArray();// => [] var array = [1, 2, 3];console.log(_.castArray(array) === array);// => true
_.clone(value)
建立 `value` 的淺層複製。
注意:此方法大致基於 結構化複製演算法,並支援複製陣列、陣列緩衝區、布林值、日期物件、映射、數字、Object
物件、正規表示式、集合、字串、符號和類型化陣列。arguments
物件的自有可列舉屬性會複製為一般物件。對於無法複製的值(例如錯誤物件、函式、DOM 節點和 WeakMaps),會傳回一個空物件。
0.1.0
value
(*):要複製的值。(*):傳回複製的值。
var objects = [{ 'a': 1 }, { 'b': 2 }]; var shallow = _.clone(objects);console.log(shallow[0] === objects[0]);// => true
_.cloneDeep(value)
此方法類似於 _.clone
,但會遞迴複製 `value`。
1.0.0
value
(*):要遞迴複製的值。(*):傳回深度複製的值。
var objects = [{ 'a': 1 }, { 'b': 2 }]; var deep = _.cloneDeep(objects);console.log(deep[0] === objects[0]);// => false
_.cloneDeepWith(value, [customizer])
此方法類似於 _.cloneWith
,但會遞迴複製 `value`。
4.0.0
value
(*):要遞迴複製的值。[customizer]
(Function):自訂複製行為的函式。(*):傳回深度複製的值。
function customizer(value) { if (_.isElement(value)) { return value.cloneNode(true); }} var el = _.cloneDeepWith(document.body, customizer); console.log(el === document.body);// => falseconsole.log(el.nodeName);// => 'BODY'console.log(el.childNodes.length);// => 20
_.cloneWith(value, [customizer])
這個方法類似 _.clone
,但它接受 `customizer`,用於產生複製的值。如果 `customizer` 傳回 `undefined`,複製會由方法處理。`customizer` 會呼叫最多四個參數;(value [, index|key, object, stack])。
4.0.0
value
(*):要複製的值。[customizer]
(Function):自訂複製行為的函式。(*):傳回複製的值。
function customizer(value) { if (_.isElement(value)) { return value.cloneNode(false); }} var el = _.cloneWith(document.body, customizer); console.log(el === document.body);// => falseconsole.log(el.nodeName);// => 'BODY'console.log(el.childNodes.length);// => 0
_.conformsTo(object, source)
檢查 `object` 是否符合 `source`,方法是呼叫 `source` 的謂詞屬性,並使用 `object` 的對應屬性值。
注意:當 `source` 部分套用時,此方法等同於 _.conforms
。
4.14.0
object
(Object):要檢查的物件。source
(Object):要符合的屬性謂詞物件。(boolean):如果 `object` 符合,傳回 `true`,否則傳回 `false`。
var object = { 'a': 1, 'b': 2 }; _.conformsTo(object, { 'b': function(n) { return n > 1; } });// => true _.conformsTo(object, { 'b': function(n) { return n > 2; } });// => false
_.eq(value, other)
對兩個值執行 SameValueZero
比較,以確定它們是否相等。
4.0.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。(boolean):如果數值相等,傳回 `true`,否則傳回 `false`。
var object = { 'a': 1 };var other = { 'a': 1 }; _.eq(object, object);// => true _.eq(object, other);// => false _.eq('a', 'a');// => true _.eq('a', Object('a'));// => false _.eq(NaN, NaN);// => true
_.gt(value, other)
檢查 value
是否大於 other
。
3.9.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。(boolean):如果 value
大於 other
,則傳回 true
,否則傳回 false
。
_.gt(3, 1);// => true _.gt(3, 3);// => false _.gt(1, 3);// => false
_.gte(value, other)
檢查 value
是否大於或等於 other
。
3.9.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。(boolean):如果 value
大於或等於 other
,則傳回 true
,否則傳回 false
。
_.gte(3, 1);// => true _.gte(3, 3);// => true _.gte(1, 3);// => false
_.isArguments(value)
檢查 value
是否可能是 arguments
物件。
0.1.0
value
(*):要檢查的值。(boolean):如果 value
是 arguments
物件,則傳回 true
,否則傳回 false
。
_.isArguments(function() { return arguments; }());// => true _.isArguments([1, 2, 3]);// => false
_.isArray(value)
檢查 value
是否分類為 Array
物件。
0.1.0
value
(*):要檢查的值。(boolean):如果 value
是陣列,則傳回 true
,否則傳回 false
。
_.isArray([1, 2, 3]);// => true _.isArray(document.body.children);// => false _.isArray('abc');// => false _.isArray(_.noop);// => false
_.isArrayBuffer(value)
檢查 value
是否分類為 ArrayBuffer
物件。
4.3.0
value
(*):要檢查的值。(布林值):如果 value
是陣列緩衝區,傳回 true
,否則傳回 false
。
_.isArrayBuffer(new ArrayBuffer(2));// => true _.isArrayBuffer(new Array(2));// => false
_.isArrayLike(value)
檢查 value
是否類似陣列。如果一個值不是函式,且具有大於或等於 0
且小於或等於 Number.MAX_SAFE_INTEGER
的整數 value.length
,則該值會被視為類似陣列。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
類似陣列,傳回 true
,否則傳回 false
。
_.isArrayLike([1, 2, 3]);// => true _.isArrayLike(document.body.children);// => true _.isArrayLike('abc');// => true _.isArrayLike(_.noop);// => false
_.isArrayLikeObject(value)
此方法類似於 _.isArrayLike
,但它也會檢查 value
是否為物件。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
是類似陣列的物件,傳回 true
,否則傳回 false
。
_.isArrayLikeObject([1, 2, 3]);// => true _.isArrayLikeObject(document.body.children);// => true _.isArrayLikeObject('abc');// => false _.isArrayLikeObject(_.noop);// => false
_.isBoolean(value)
檢查 value
是否分類為布林值基本型別或物件。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是布林值,傳回 true
,否則傳回 false
。
_.isBoolean(false);// => true _.isBoolean(null);// => false
_.isBuffer(value)
檢查 value
是否為緩衝區。
4.3.0
value
(*):要檢查的值。(布林值):如果 value
是緩衝區,則傳回 true
,否則傳回 false
。
_.isBuffer(new Buffer(2));// => true _.isBuffer(new Uint8Array(2));// => false
_.isDate(value)
檢查 value
是否分類為 Date
物件。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是日期物件,則傳回 true
,否則傳回 false
。
_.isDate(new Date);// => true _.isDate('Mon April 23 2012');// => false
_.isElement(value)
檢查 value
是否可能是 DOM 元素。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是 DOM 元素,則傳回 true
,否則傳回 false
。
_.isElement(document.body);// => true _.isElement('<body>');// => false
_.isEmpty(value)
檢查 value
是否為空物件、集合、映射或集合。
如果物件沒有自己的可列舉字串鍵值屬性,則會被視為空物件。
陣列值(例如 arguments
物件、陣列、緩衝區、字串或類 jQuery 的集合)如果 length
為 0
,則視為空值。同樣地,如果 size
為 0
,則視地圖和集合為空值。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
為空值,則傳回 true
,否則傳回 false
。
_.isEmpty(null);// => true _.isEmpty(true);// => true _.isEmpty(1);// => true _.isEmpty([1, 2, 3]);// => false _.isEmpty({ 'a': 1 });// => false
_.isEqual(value, other)
針對兩個值執行深入比較,以判斷它們是否相等。
注意:此方法支援比較陣列、陣列緩衝區、布林值、日期物件、錯誤物件、地圖、數字、Object
物件、正規表示式、集合、字串、符號和類型化陣列。Object
物件會根據它們自己的可列舉屬性(而非繼承的屬性)進行比較。函式和 DOM 節點會根據嚴格相等性(即 ===
)進行比較。
0.1.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。(boolean):如果數值相等,傳回 `true`,否則傳回 `false`。
var object = { 'a': 1 };var other = { 'a': 1 }; _.isEqual(object, other);// => true object === other;// => false
_.isEqualWith(value, other, [customizer])
此方法類似於 _.isEqual
,但它接受 customizer
,而 customizer
會呼叫以比較值。如果 customizer
傳回 undefined
,則比較會由方法處理。customizer
最多會呼叫六個引數:(objValue, othValue [, index|key, object, other, stack])。
4.0.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。[customizer]
(函式):自訂比較函式。(boolean):如果數值相等,傳回 `true`,否則傳回 `false`。
function isGreeting(value) { return /^h(?:i|ello)$/.test(value);} function customizer(objValue, othValue) { if (isGreeting(objValue) && isGreeting(othValue)) { return true; }} var array = ['hello', 'goodbye'];var other = ['hi', 'goodbye']; _.isEqualWith(array, other, customizer);// => true
_.isError(value)
檢查 value
是否為 Error
、EvalError
、RangeError
、ReferenceError
、SyntaxError
、TypeError
或 URIError
物件。
3.0.0
value
(*):要檢查的值。(布林值):如果 value
是錯誤物件,傳回 true
,否則傳回 false
。
_.isError(new Error);// => true _.isError(Error);// => false
_.isFinite(value)
檢查 value
是否為有限的原始數字。
注意:此方法基於 Number.isFinite
。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是有限數字,傳回 true
,否則傳回 false
。
_.isFinite(3);// => true _.isFinite(Number.MIN_VALUE);// => true _.isFinite(Infinity);// => false _.isFinite('3');// => false
_.isFunction(value)
檢查 value
是否分類為 Function
物件。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是函式,傳回 true
,否則傳回 false
。
_.isFunction(_);// => true _.isFunction(/abc/);// => false
_.isInteger(value)
檢查 value
是否為整數。
注意:此方法基於 Number.isInteger
。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
是整數,則傳回 true
,否則傳回 false
。
_.isInteger(3);// => true _.isInteger(Number.MIN_VALUE);// => false _.isInteger(Infinity);// => false _.isInteger('3');// => false
_.isLength(value)
檢查 value
是否為有效的類陣列長度。
注意:此方法大致基於 ToLength
。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
是有效長度,則傳回 true
,否則傳回 false
。
_.isLength(3);// => true _.isLength(Number.MIN_VALUE);// => false _.isLength(Infinity);// => false _.isLength('3');// => false
_.isMap(value)
檢查 value
是否分類為 Map
物件。
4.3.0
value
(*):要檢查的值。(布林值):如果 value
是 map,則傳回 true
,否則傳回 false
。
_.isMap(new Map);// => true _.isMap(new WeakMap);// => false
_.isMatch(object, source)
在 object
和 source
之間執行部分深度比較,以確定 object
是否包含等效的屬性值。
注意:當 source
部分套用時,此方法等同於 _.matches
。
部分比較會將空的陣列和空的物件 source
值分別與任何陣列或物件值相符。請參閱 _.isEqual
以取得支援的值比較清單。
3.0.0
object
(Object):要檢查的物件。source
(物件):要比對屬性值的物件。(布林值):如果 object
相符,傳回 true
,否則傳回 false
。
var object = { 'a': 1, 'b': 2 }; _.isMatch(object, { 'b': 2 });// => true _.isMatch(object, { 'b': 1 });// => false
_.isMatchWith(object, source, [customizer])
此方法類似 _.isMatch
,但它接受 customizer
,用於比對值。如果 customizer
傳回 undefined
,比對將由方法處理。customizer
會呼叫五個引數:(objValue, srcValue, index|key, object, source)。
4.0.0
object
(Object):要檢查的物件。source
(物件):要比對屬性值的物件。[customizer]
(函式):自訂比較函式。(布林值):如果 object
相符,傳回 true
,否則傳回 false
。
function isGreeting(value) { return /^h(?:i|ello)$/.test(value);} function customizer(objValue, srcValue) { if (isGreeting(objValue) && isGreeting(srcValue)) { return true; }} var object = { 'greeting': 'hello' };var source = { 'greeting': 'hi' }; _.isMatchWith(object, source, customizer);// => true
_.isNaN(value)
檢查 value
是否為 NaN
。
注意:此方法基於 Number.isNaN
,與全域 isNaN
不同,後者會為 undefined
和其他非數字值傳回 true
。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
為 NaN
,傳回 true
,否則傳回 false
。
_.isNaN(NaN);// => true _.isNaN(new Number(NaN));// => true isNaN(undefined);// => true _.isNaN(undefined);// => false
_.isNative(value)
檢查 value
是否為原生函式。
注意:此方法無法在存在 core-js 套件時可靠地偵測原生函式,因為 core-js 會規避此類偵測。儘管有許多要求,core-js 維護者已明確表示:任何修正偵測的嘗試都會受到阻礙。因此,我們別無選擇,只能擲回錯誤。遺憾的是,這也會影響依賴 core-js 的套件,例如 babel-polyfill。
3.0.0
value
(*):要檢查的值。(布林值):如果 value
是原生函數,則傳回 true
,否則傳回 false
。
_.isNative(Array.prototype.push);// => true _.isNative(_);// => false
_.isNil(value)
檢查 value
是否為 null
或 undefined
。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
為空值,則傳回 true
,否則傳回 false
。
_.isNil(null);// => true _.isNil(void 0);// => true _.isNil(NaN);// => false
_.isNull(value)
檢查 value
是否為 null
。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
為 null
,則傳回 true
,否則傳回 false
。
_.isNull(null);// => true _.isNull(void 0);// => false
_.isNumber(value)
檢查 value
是否分類為 Number
基本型別或物件。
注意:若要排除分類為數字的 Infinity
、-Infinity
和 NaN
,請使用 _.isFinite
方法。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
為數字,則傳回 true
,否則傳回 false
。
_.isNumber(3);// => true _.isNumber(Number.MIN_VALUE);// => true _.isNumber(Infinity);// => true _.isNumber('3');// => false
_.isObject(value)
檢查 value
是否為 Object
的 語言類型。(例如陣列、函式、物件、正規表示式、new Number(0)
和 new String('')
)
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是物件,傳回 true
,否則傳回 false
。
_.isObject({});// => true _.isObject([1, 2, 3]);// => true _.isObject(_.noop);// => true _.isObject(null);// => false
_.isObjectLike(value)
檢查 value
是否為類物件。如果 value
不是 null
且 typeof
結果為「object」,則該值為類物件。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
是類物件,傳回 true
,否則傳回 false
。
_.isObjectLike({});// => true _.isObjectLike([1, 2, 3]);// => true _.isObjectLike(_.noop);// => false _.isObjectLike(null);// => false
_.isPlainObject(value)
檢查 value
是否為純粹物件,也就是由 Object
建構函式建立的物件,或 [[Prototype]]
為 null
的物件。
0.8.0
value
(*):要檢查的值。(布林值):如果 value
是純粹物件,傳回 true
,否則傳回 false
。
function Foo() { this.a = 1;} _.isPlainObject(new Foo);// => false _.isPlainObject([1, 2, 3]);// => false _.isPlainObject({ 'x': 0, 'y': 0 });// => true _.isPlainObject(Object.create(null));// => true
_.isRegExp(value)
檢查 value
是否分類為 RegExp
物件。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是正則表達式,則傳回 true
,否則傳回 false
。
_.isRegExp(/abc/);// => true _.isRegExp('/abc/');// => false
_.isSafeInteger(value)
檢查 value
是否為安全整數。如果整數是 IEEE-754 雙精度數字,且不是捨入後的非安全整數,則該整數為安全整數。
注意:此方法是根據 Number.isSafeInteger
建立的。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
是安全整數,則傳回 true
,否則傳回 false
。
_.isSafeInteger(3);// => true _.isSafeInteger(Number.MIN_VALUE);// => false _.isSafeInteger(Infinity);// => false _.isSafeInteger('3');// => false
_.isSet(value)
檢查 value
是否分類為 Set
物件。
4.3.0
value
(*):要檢查的值。(布林值):如果 value
是集合,則傳回 true
,否則傳回 false
。
_.isSet(new Set);// => true _.isSet(new WeakSet);// => false
_.isString(value)
檢查 value
是否分類為 String
基本型別或物件。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是字串,則傳回 true
,否則傳回 false
。
_.isString('abc');// => true _.isString(1);// => false
_.isSymbol(value)
檢查 value
是否分類為 Symbol
基本型別或物件。
4.0.0
value
(*):要檢查的值。(布林值):如果 value
是符號,則傳回 true
,否則傳回 false
。
_.isSymbol(Symbol.iterator);// => true _.isSymbol('abc');// => false
_.isTypedArray(value)
檢查 value
是否分類為類型化陣列。
3.0.0
value
(*):要檢查的值。(布林值):如果 value
是類型化陣列,則傳回 true
,否則傳回 false
。
_.isTypedArray(new Uint8Array);// => true _.isTypedArray([]);// => false
_.isUndefined(value)
檢查 value
是否為 undefined
。
0.1.0
value
(*):要檢查的值。(布林值):如果 value
是 undefined
,則傳回 true
,否則傳回 false
。
_.isUndefined(void 0);// => true _.isUndefined(null);// => false
_.isWeakMap(value)
檢查 value
是否分類為 WeakMap
物件。
4.3.0
value
(*):要檢查的值。(布林值):如果 value
是弱映射,則傳回 true
,否則傳回 false
。
_.isWeakMap(new WeakMap);// => true _.isWeakMap(new Map);// => false
_.isWeakSet(value)
檢查 value
是否分類為 WeakSet
物件。
4.3.0
value
(*):要檢查的值。(boolean):如果 value
是弱集合,則傳回 true
,否則傳回 false
。
_.isWeakSet(new WeakSet);// => true _.isWeakSet(new Set);// => false
_.lt(value, other)
檢查 value
是否小於 other
。
3.9.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。(boolean):如果 value
小於 other
,則傳回 true
,否則傳回 false
。
_.lt(1, 3);// => true _.lt(3, 3);// => false _.lt(3, 1);// => false
_.lte(value, other)
檢查 value
是否小於或等於 other
。
3.9.0
value
(*):要比較的數值。other
(*):要比較的另一個數值。(boolean):如果 value
小於或等於 other
,則傳回 true
,否則傳回 false
。
_.lte(1, 3);// => true _.lte(3, 3);// => true _.lte(3, 1);// => false
_.toArray(value)
將 value
轉換為陣列。
0.1.0
value
(*):要轉換的值。(Array):傳回轉換後的陣列。
_.toArray({ 'a': 1, 'b': 2 });// => [1, 2] _.toArray('abc');// => ['a', 'b', 'c'] _.toArray(1);// => [] _.toArray(null);// => []
_.toFinite(value)
將 value
轉換為有限數字。
4.12.0
value
(*):要轉換的值。(數字):傳回轉換後的數字。
_.toFinite(3.2);// => 3.2 _.toFinite(Number.MIN_VALUE);// => 5e-324 _.toFinite(Infinity);// => 1.7976931348623157e+308 _.toFinite('3.2');// => 3.2
_.toInteger(value)
將 value
轉換為整數。
注意:此方法大致基於 ToInteger
。
4.0.0
value
(*):要轉換的值。(數字):傳回轉換後的整數。
_.toInteger(3.2);// => 3 _.toInteger(Number.MIN_VALUE);// => 0 _.toInteger(Infinity);// => 1.7976931348623157e+308 _.toInteger('3.2');// => 3
_.toLength(value)
將 value
轉換為適合用作類似陣列物件長度的整數。
注意:此方法基於 ToLength
。
4.0.0
value
(*):要轉換的值。(數字):傳回轉換後的整數。
_.toLength(3.2);// => 3 _.toLength(Number.MIN_VALUE);// => 0 _.toLength(Infinity);// => 4294967295 _.toLength('3.2');// => 3
_.toNumber(value)
將 value
轉換為數字。
4.0.0
value
(*):要處理的值。(數字):傳回數字。
_.toNumber(3.2);// => 3.2 _.toNumber(Number.MIN_VALUE);// => 5e-324 _.toNumber(Infinity);// => Infinity _.toNumber('3.2');// => 3.2
_.toPlainObject(value)
將 value
轉換為純粹物件,將 value
繼承的列舉字串鍵值屬性扁平化為純粹物件的自有屬性。
3.0.0
value
(*):要轉換的值。(物件):傳回轉換後的純粹物件。
function Foo() { this.b = 2;} Foo.prototype.c = 3; _.assign({ 'a': 1 }, new Foo);// => { 'a': 1, 'b': 2 } _.assign({ 'a': 1 }, _.toPlainObject(new Foo));// => { 'a': 1, 'b': 2, 'c': 3 }
「數學」方法
_.add(augend, addend)
加總兩個數字。
3.4.0
augend
(數字): 加法中的第一個數字。addend
(數字): 加法中的第二個數字。(數字): 傳回總和。
_.add(6, 4);// => 10
_.ceil(number, [precision=0])
計算 number
無條件進位到 precision
。
3.10.0
number
(數字): 要無條件進位的數字。[precision=0]
(數字): 要無條件進位的精度。(數字): 傳回無條件進位的數字。
_.ceil(4.006);// => 5 _.ceil(6.004, 2);// => 6.01 _.ceil(6040, -2);// => 6100
_.divide(dividend, divisor)
除兩個數字。
4.7.0
被除數
(數字):除法中的第一個數字。除數
(數字):除法中的第二個數字。(數字):傳回商數。
_.divide(6, 4);// => 1.5
_.floor(數字, [精確度=0])
計算 數字
四捨五入到 精確度
。
3.10.0
數字
(數字):要四捨五入的數字。[精確度=0]
(數字):要四捨五入到的精確度。(數字):傳回四捨五入後的數字。
_.floor(4.006);// => 4 _.floor(0.046, 2);// => 0.04 _.floor(4060, -2);// => 4000
_.max(陣列)
計算 陣列
的最大值。如果 陣列
為空或假值,則傳回 undefined
。
0.1.0
陣列
(陣列):要迭代的陣列。(*):傳回最大值。
_.max([4, 2, 8, 6]);// => 8 _.max([]);// => undefined
_.maxBy(陣列, [迭代函數=_.identity])
此方法類似於 _.max
,但它接受 `iteratee`,它會針對 `array` 中的每個元素呼叫,以產生用於對值進行排序的準則。iteratee 會使用一個參數呼叫:(value)。
4.0.0
陣列
(陣列):要迭代的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(*):傳回最大值。
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; });// => { 'n': 2 } // The `_.property` iteratee shorthand._.maxBy(objects, 'n');// => { 'n': 2 }
_.meanBy(array, [iteratee=_.identity])
此方法類似於 _.mean
,但它接受 `iteratee`,它會針對 `array` 中的每個元素呼叫,以產生要取平均值的值。iteratee 會使用一個參數呼叫:(value)。
4.7.0
陣列
(陣列):要迭代的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(數字):傳回平均值。
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.meanBy(objects, function(o) { return o.n; });// => 5 // The `_.property` iteratee shorthand._.meanBy(objects, 'n');// => 5
_.min(array)
計算 `array` 的最小值。如果 `array` 為空或為假值,則傳回 `undefined`。
0.1.0
陣列
(陣列):要迭代的陣列。(*):傳回最小值。
_.min([4, 2, 8, 6]);// => 2 _.min([]);// => undefined
_.minBy(array, [iteratee=_.identity])
此方法類似於 _.min
,但它接受 `iteratee`,它會針對 `array` 中的每個元素呼叫,以產生用於對值進行排序的準則。iteratee 會使用一個參數呼叫:(value)。
4.0.0
陣列
(陣列):要迭代的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(*):傳回最小值。
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; });// => { 'n': 1 } // The `_.property` iteratee shorthand._.minBy(objects, 'n');// => { 'n': 1 }
_.multiply(multiplier, multiplicand)
將兩個數字相乘。
4.7.0
multiplier
(數字):相乘的第一個數字。multiplicand
(數字):相乘的第二個數字。(數字):傳回乘積。
_.multiply(6, 4);// => 24
_.round(number, [precision=0])
計算將 number
四捨五入到 precision
。
3.10.0
number
(數字):要四捨五入的數字。[precision=0]
(數字):要四捨五入到的精度。(數字):傳回四捨五入後的數字。
_.round(4.006);// => 4 _.round(4.006, 2);// => 4.01 _.round(4060, -2);// => 4100
_.subtract(minuend, subtrahend)
減去兩個數字。
4.0.0
minuend
(數字):減法的第一個數字。subtrahend
(數字):減法的第二個數字。(數字):傳回差值。
_.subtract(6, 4);// => 2
_.sumBy(array, [iteratee=_.identity])
此方法類似 _.sum
,但它接受 iteratee
,而 iteratee
會呼叫陣列中的每個元素,以產生要加總的值。iteratee
會呼叫一個引數:(value)。
4.0.0
陣列
(陣列):要迭代的陣列。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(數字):傳回總和。
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.sumBy(objects, function(o) { return o.n; });// => 20 // The `_.property` iteratee shorthand._.sumBy(objects, 'n');// => 20
「數字」方法
_.clamp(number, [lower], upper)
將 number
限制在包含 lower
和 upper
界線內。
4.0.0
number
(數字):要限制的數字。[lower]
(數字):下界線。upper
(數字):上界線。(數字):傳回限制後的數字。
_.clamp(-10, -5, 5);// => -5 _.clamp(10, -5, 5);// => 5
_.inRange(number, [start=0], end)
檢查 n
是否介於 start
和 end
之間(但未包含 end
)。如果未指定 end
,則將其設定為 start
,並將 start
設定為 0
。如果 start
大於 end
,則交換參數以支援負值範圍。
3.3.0
number
(數字):要檢查的數字。[start=0]
(數字):範圍的開頭。end
(數字):範圍的結尾。(布林值):如果 number
在範圍內,則傳回 true
,否則傳回 false
。
_.inRange(3, 2, 4);// => true _.inRange(4, 8);// => true _.inRange(4, 2);// => false _.inRange(2, 2);// => false _.inRange(1.2, 2);// => true _.inRange(5.2, 4);// => false _.inRange(-3, -2, -6);// => true
_.random([lower=0], [upper=1], [floating])
產生介於包含 lower
和 upper
界線之間的隨機數字。如果只提供一個參數,則傳回介於 0
和給定數字之間的數字。如果 floating
為 true
,或 lower
或 upper
為浮點數,則傳回浮點數,而非整數。
注意: JavaScript 遵循 IEEE-754 標準來解析浮點數值,這可能會產生意外的結果。
0.7.0
[lower=0]
(數字):下界。[upper=1]
(數字):上界。[floating]
(布林值):指定傳回浮點數。(數字):傳回隨機數字。
_.random(0, 5);// => an integer between 0 and 5 _.random(5);// => also an integer between 0 and 5 _.random(5, true);// => a floating-point number between 0 and 5 _.random(1.2, 5.2);// => a floating-point number between 1.2 and 5.2
「物件」方法
_.assign(object, [sources])
將來源物件的自身可列舉字串鍵值屬性指定給目標物件。來源物件從左至右套用。後續來源會覆寫先前來源的屬性指定。
注意:此方法會改變 object
,且大致基於 Object.assign
。
0.10.0
object
(Object):目標物件。[sources]
(...Object):來源物件。(Object):傳回 object
。
function Foo() { this.a = 1;} function Bar() { this.c = 3;} Foo.prototype.b = 2;Bar.prototype.d = 4; _.assign({ 'a': 0 }, new Foo, new Bar);// => { 'a': 1, 'c': 3 }
_.assignIn(object, [sources])
此方法類似於 _.assign
,但會遍歷來源物件的自身和繼承屬性。
注意:此方法會改變 object
。
4.0.0
_.extend
object
(Object):目標物件。[sources]
(...Object):來源物件。(Object):傳回 object
。
function Foo() { this.a = 1;} function Bar() { this.c = 3;} Foo.prototype.b = 2;Bar.prototype.d = 4; _.assignIn({ 'a': 0 }, new Foo, new Bar);// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
_.assignInWith(object, sources, [customizer])
此方法類似於 _.assignIn
,但會接受 customizer
,並呼叫此函式來產生指定的值。如果 customizer
傳回 undefined
,指定動作將由方法處理。customizer
會以五個參數呼叫:(objValue, srcValue, key, object, source)。
注意:此方法會改變 object
。
4.0.0
_.extendWith
object
(Object):目標物件。sources
(...Object):來源物件。[customizer]
(Function):自訂指定值的函式。(Object):傳回 object
。
function customizer(objValue, srcValue) { return _.isUndefined(objValue) ? srcValue : objValue;} var defaults = _.partialRight(_.assignInWith, customizer); defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });// => { 'a': 1, 'b': 2 }
_.assignWith(object, sources, [customizer])
此方法類似於 _.assign
,但它接受 customizer
,用於產生已指派的值。如果 customizer
傳回 undefined
,則指派會由方法處理。customizer
會呼叫五個參數:(objValue, srcValue, key, object, source)。
注意:此方法會改變 object
。
4.0.0
object
(Object):目標物件。sources
(...Object):來源物件。[customizer]
(Function):自訂指定值的函式。(Object):傳回 object
。
function customizer(objValue, srcValue) { return _.isUndefined(objValue) ? srcValue : objValue;} var defaults = _.partialRight(_.assignWith, customizer); defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });// => { 'a': 1, 'b': 2 }
_.at(object, [paths])
根據 object
的 paths
建立一個值陣列。
1.0.0
object
(Object):要迭代的物件。[paths]
(...(string|string[])):要挑選的屬性路徑。(Array):傳回已挑選的值。
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; _.at(object, ['a[0].b.c', 'a[1]']);// => [3, 4]
_.create(prototype, [properties])
建立一個繼承自 prototype
物件的物件。如果給定 properties
物件,其可列舉的字串鍵值屬性會指派給已建立的物件。
2.3.0
prototype
(Object):要繼承的物件。[properties]
(Object):要指派給物件的屬性。(物件):傳回新的物件。
function Shape() { this.x = 0; this.y = 0;} function Circle() { Shape.call(this);} Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle}); var circle = new Circle;circle instanceof Circle;// => true circle instanceof Shape;// => true
_.defaults(object, [sources])
將來源物件中可列舉的字串金鑰自有和繼承的屬性指派給目標物件中所有解析為 undefined
的目標屬性。來源物件由左至右套用。一旦設定屬性,則會忽略同一個屬性的其他值。
注意:此方法會改變 object
。
0.1.0
object
(Object):目標物件。[sources]
(...Object):來源物件。(Object):傳回 object
。
_.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });// => { 'a': 1, 'b': 2 }
_.defaultsDeep(object, [sources])
此方法類似於 _.defaults
,但會遞迴指派預設屬性。
注意:此方法會改變 object
。
3.10.0
object
(Object):目標物件。[sources]
(...Object):來源物件。(Object):傳回 object
。
_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });// => { 'a': { 'b': 2, 'c': 3 } }
_.findKey(object, [predicate=_.identity])
此方法類似於 _.find
,但會傳回第一個元素的鍵,而不是元素本身,且 predicate
會傳回真值。
1.1.0
object
(Object):要檢查的物件。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(*):傳回配對元素的鍵,否則為 undefined
。
var users = { 'barney': { 'age': 36, 'active': true }, 'fred': { 'age': 40, 'active': false }, 'pebbles': { 'age': 1, 'active': true }}; _.findKey(users, function(o) { return o.age < 40; });// => 'barney' (iteration order is not guaranteed) // The `_.matches` iteratee shorthand._.findKey(users, { 'age': 1, 'active': true });// => 'pebbles' // The `_.matchesProperty` iteratee shorthand._.findKey(users, ['active', false]);// => 'fred' // The `_.property` iteratee shorthand._.findKey(users, 'active');// => 'barney'
_.findLastKey(object, [predicate=_.identity])
此方法類似於 _.findKey
,但會以相反順序迭代集合中的元素。
2.0.0
object
(Object):要檢查的物件。[predicate=_.identity]
(函式):每個反覆呼叫的函式。(*):傳回配對元素的鍵,否則為 undefined
。
var users = { 'barney': { 'age': 36, 'active': true }, 'fred': { 'age': 40, 'active': false }, 'pebbles': { 'age': 1, 'active': true }}; _.findLastKey(users, function(o) { return o.age < 40; });// => returns 'pebbles' assuming `_.findKey` returns 'barney' // The `_.matches` iteratee shorthand._.findLastKey(users, { 'age': 36, 'active': true });// => 'barney' // The `_.matchesProperty` iteratee shorthand._.findLastKey(users, ['active', false]);// => 'fred' // The `_.property` iteratee shorthand._.findLastKey(users, 'active');// => 'pebbles'
_.forIn(object, [iteratee=_.identity])
遍歷物件可列舉的字串金鑰的自身和繼承屬性,並對每個屬性呼叫 iteratee
。呼叫 iteratee 時會傳入三個參數:(value, key, object)。Iteratee 函式可以透過明確傳回 false
來提早結束遍歷。
0.3.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(Object):傳回 object
。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forIn(new Foo, function(value, key) { console.log(key);});// => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
_.forInRight(object, [iteratee=_.identity])
此方法類似於 _.forIn
,但遍歷 object
的屬性順序相反。
2.0.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(Object):傳回 object
。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forInRight(new Foo, function(value, key) { console.log(key);});// => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
_.forOwn(object, [iteratee=_.identity])
遍歷物件可列舉的自身字串金鑰屬性,並對每個屬性呼叫 iteratee
。呼叫 iteratee 時會傳入三個參數:(value, key, object)。Iteratee 函式可以透過明確傳回 false
來提早結束遍歷。
0.3.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(Object):傳回 object
。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forOwn(new Foo, function(value, key) { console.log(key);});// => Logs 'a' then 'b' (iteration order is not guaranteed).
_.forOwnRight(object, [iteratee=_.identity])
此方法類似於 _.forOwn
,但遍歷 object
的屬性順序相反。
2.0.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(Object):傳回 object
。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forOwnRight(new Foo, function(value, key) { console.log(key);});// => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
_.functions(object)
建立一個陣列,包含 `object` 自身可列舉屬性的函式屬性名稱。
0.1.0
object
(Object):要檢查的物件。(陣列):傳回函式名稱。
function Foo() { this.a = _.constant('a'); this.b = _.constant('b');} Foo.prototype.c = _.constant('c'); _.functions(new Foo);// => ['a', 'b']
_.functionsIn(object)
建立一個陣列,包含 `object` 自身和繼承的可列舉屬性的函式屬性名稱。
4.0.0
object
(Object):要檢查的物件。(陣列):傳回函式名稱。
function Foo() { this.a = _.constant('a'); this.b = _.constant('b');} Foo.prototype.c = _.constant('c'); _.functionsIn(new Foo);// => ['a', 'b', 'c']
_.get(object, path, [defaultValue])
取得 `object` 中 `path` 的值。如果解析出的值為 `undefined`,則會傳回 `defaultValue` 取代。
3.7.0
object
(物件):要查詢的物件。path
(陣列或字串):要取得屬性的路徑。[defaultValue]
(*):解析出的值為 `undefined` 時傳回的值。(*):傳回解析出的值。
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.get(object, 'a[0].b.c');// => 3 _.get(object, ['a', '0', 'b', 'c']);// => 3 _.get(object, 'a.b.c', 'default');// => 'default'
_.has(object, path)
檢查 `path` 是否為 `object` 的直接屬性。
0.1.0
object
(物件):要查詢的物件。path
(陣列或字串):要檢查的路徑。(布林值):如果 `path` 存在,傳回 `true`,否則傳回 `false`。
var object = { 'a': { 'b': 2 } };var other = _.create({ 'a': _.create({ 'b': 2 }) }); _.has(object, 'a');// => true _.has(object, 'a.b');// => true _.has(object, ['a', 'b']);// => true _.has(other, 'a');// => false
_.hasIn(object, path)
檢查 path
是否為 object
的直接或繼承屬性。
4.0.0
object
(物件):要查詢的物件。path
(陣列或字串):要檢查的路徑。(布林值):如果 `path` 存在,傳回 `true`,否則傳回 `false`。
var object = _.create({ 'a': _.create({ 'b': 2 }) }); _.hasIn(object, 'a');// => true _.hasIn(object, 'a.b');// => true _.hasIn(object, ['a', 'b']);// => true _.hasIn(object, 'b');// => false
_.invert(object)
建立一個物件,其組成包含 object
的反轉鍵值。如果 object
包含重複值,後續值會覆寫先前值的屬性指定。
0.7.0
object
(Object): 要反轉的物件。(Object): 傳回新的反轉物件。
var object = { 'a': 1, 'b': 2, 'c': 1 }; _.invert(object);// => { '1': 'c', '2': 'b' }
_.invertBy(object, [iteratee=_.identity])
此方法類似於 _.invert
,但反轉物件會根據執行 object
的每個元素的 iteratee
結果產生。每個反轉鍵值對應的反轉值是負責產生反轉值的鍵值陣列。iteratee 會呼叫一個引數:(value)。
4.1.0
object
(Object): 要反轉的物件。[iteratee=_.identity]
(函式):每個元素呼叫的 iteratee。(Object): 傳回新的反轉物件。
var object = { 'a': 1, 'b': 2, 'c': 1 }; _.invertBy(object);// => { '1': ['a', 'c'], '2': ['b'] } _.invertBy(object, function(value) { return 'group' + value;});// => { 'group1': ['a', 'c'], 'group2': ['b'] }
_.invoke(object, path, [args])
呼叫 object
的 path
方法。
4.0.0
object
(物件):要查詢的物件。path
(Array|string): 要呼叫的方法路徑。[args]
(...*): 要呼叫方法的引數。(*): 傳回呼叫方法的結果。
var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; _.invoke(object, 'a[0].b.c.slice', 1, 3);// => [2, 3]
_.keys(object)
建立一個陣列,包含 object
自有可列舉的屬性名稱。
注意:非物件值會被強制轉換為物件。更多詳細資訊,請參閱 ES 規範。
0.1.0
object
(物件):要查詢的物件。(陣列):傳回屬性名稱陣列。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.keys(new Foo);// => ['a', 'b'] (iteration order is not guaranteed) _.keys('hi');// => ['0', '1']
_.keysIn(object)
建立一個陣列,包含 object
自有和繼承的可列舉屬性名稱。
注意:非物件值會被強制轉換為物件。
3.0.0
object
(物件):要查詢的物件。(陣列):傳回屬性名稱陣列。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.keysIn(new Foo);// => ['a', 'b', 'c'] (iteration order is not guaranteed)
_.mapKeys(object, [iteratee=_.identity])
_.mapValues
的反向操作;這個方法會建立一個物件,其值與 object
相同,而其金鑰則透過執行 object
的每個自有可列舉字串金鑰屬性來產生,並傳遞給 iteratee
。iteratee
會使用三個參數呼叫:(value, key, object)。
3.8.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(物件):傳回新的已對應物件。
_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { return key + value;});// => { 'a1': 1, 'b2': 2 }
_.mapValues(object, [iteratee=_.identity])
建立一個物件,其鍵與 object
相同,而其值則透過執行 object
的每個可列舉字串鍵屬性並傳遞至 iteratee
而產生。iteratee 會使用三個參數呼叫
(值、鍵、物件).
2.4.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(物件):傳回新的已對應物件。
var users = { 'fred': { 'user': 'fred', 'age': 40 }, 'pebbles': { 'user': 'pebbles', 'age': 1 }}; _.mapValues(users, function(o) { return o.age; });// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) // The `_.property` iteratee shorthand._.mapValues(users, 'age');// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
_.merge(object, [sources])
此方法類似於 _.assign
,但其會遞迴合併來源物件的可列舉字串鍵屬性(包含繼承的屬性)至目標物件。如果目標值存在,則會跳過會解析為 undefined
的來源屬性。陣列和一般物件屬性會遞迴合併。其他物件和值類型會透過指定覆寫。來源物件會從左至右套用。後續來源會覆寫先前來源的屬性指定。
注意:此方法會改變 object
。
0.5.0
object
(Object):目標物件。[sources]
(...Object):來源物件。(Object):傳回 object
。
var object = { 'a': [{ 'b': 2 }, { 'd': 4 }]}; var other = { 'a': [{ 'c': 3 }, { 'e': 5 }]}; _.merge(object, other);// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
_.mergeWith(object, sources, customizer)
此方法類似於 _.merge
,但其接受 customizer
,而 customizer
會呼叫來產生目標和來源屬性的合併值。如果 customizer
傳回 undefined
,合併將由方法處理。customizer
會使用六個參數呼叫
(objValue, srcValue, key, object, source, stack).
注意:此方法會改變 object
。
4.0.0
object
(Object):目標物件。sources
(...Object):來源物件。customizer
(函數): 自訂指定值的函數。(Object):傳回 object
。
function customizer(objValue, srcValue) { if (_.isArray(objValue)) { return objValue.concat(srcValue); }} var object = { 'a': [1], 'b': [2] };var other = { 'a': [3], 'b': [4] }; _.mergeWith(object, other, customizer);// => { 'a': [1, 3], 'b': [2, 4] }
_.omit(object, [paths])
與 _.pick
相反;此方法會建立一個物件,其組成來自 object
的可列舉自有和繼承屬性路徑,且這些路徑未被省略。
注意:此方法比 _.pick
慢很多。
0.1.0
object
(物件): 來源物件。[paths]
(...(字串|字串陣列)): 要省略的屬性路徑。(物件):傳回新的物件。
var object = { 'a': 1, 'b': '2', 'c': 3 }; _.omit(object, ['a', 'c']);// => { 'b': '2' }
_.omitBy(object, [predicate=_.identity])
與 _.pickBy
相反;此方法會建立一個物件,其組成來自 object
的可列舉自有和繼承字串鍵值屬性,且 predicate
沒有為其傳回真值。此謂詞會呼叫兩個參數:(value, key)。
4.0.0
object
(物件): 來源物件。[predicate=_.identity]
(函數): 每個屬性呼叫的函數。(物件):傳回新的物件。
var object = { 'a': 1, 'b': '2', 'c': 3 }; _.omitBy(object, _.isNumber);// => { 'b': '2' }
_.pick(object, [paths])
建立一個物件,其組成來自挑選的 object
屬性。
0.1.0
object
(物件): 來源物件。[paths]
(...(string|string[])):要挑選的屬性路徑。(物件):傳回新的物件。
var object = { 'a': 1, 'b': '2', 'c': 3 }; _.pick(object, ['a', 'c']);// => { 'a': 1, 'c': 3 }
_.pickBy(object, [predicate=_.identity])
建立一個物件,其組成來自 object
屬性,而 predicate
會回傳真值。此謂詞會呼叫兩個引數:(value, key)。
4.0.0
object
(物件): 來源物件。[predicate=_.identity]
(函數): 每個屬性呼叫的函數。(物件):傳回新的物件。
var object = { 'a': 1, 'b': '2', 'c': 3 }; _.pickBy(object, _.isNumber);// => { 'a': 1, 'c': 3 }
_.result(object, path, [defaultValue])
此方法類似於 _.get
,但如果已解析的值為函式,則會呼叫此函式,並使用其父物件的 this
繫結,並回傳其結果。
0.1.0
object
(物件):要查詢的物件。path
(陣列|字串):要解析的屬性路徑。[defaultValue]
(*):解析出的值為 `undefined` 時傳回的值。(*):傳回解析出的值。
var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; _.result(object, 'a[0].b.c1');// => 3 _.result(object, 'a[0].b.c2');// => 4 _.result(object, 'a[0].b.c3', 'default');// => 'default' _.result(object, 'a[0].b.c3', _.constant('default'));// => 'default'
_.set(object, path, value)
設定 object
的 path
值。如果 path
的一部分不存在,則會建立。會為遺失的索引屬性建立陣列,而會為所有其他遺失的屬性建立物件。使用 _.setWith
自訂 path
建立。
注意:此方法會改變 object
。
3.7.0
object
(物件):要修改的物件。path
(陣列|字串):要設定的屬性路徑。value
(*):要設定的值。(Object):傳回 object
。
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.set(object, 'a[0].b.c', 4);console.log(object.a[0].b.c);// => 4 _.set(object, ['x', '0', 'y', 'z'], 5);console.log(object.x[0].y.z);// => 5
_.setWith(object, path, value, [customizer])
此方法類似於 _.set
,但它接受 customizer
,用於產生 path
的物件。如果 customizer
傳回 undefined
,路徑建立將由方法處理。customizer
會呼叫三個參數:(nsValue, key, nsObject)。
注意:此方法會改變 object
。
4.0.0
object
(物件):要修改的物件。path
(陣列|字串):要設定的屬性路徑。value
(*):要設定的值。[customizer]
(Function):自訂指定值的函式。(Object):傳回 object
。
var object = {}; _.setWith(object, '[0][1]', 'a', Object);// => { '0': { '1': 'a' } }
_.toPairs(object)
為 object
建立一個由自身可列舉的字串鍵值對陣列,可供 _.fromPairs
使用。如果 object
是 map 或 set,則傳回其項目。
4.0.0
_.entries
object
(物件):要查詢的物件。(陣列):傳回鍵值對。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.toPairs(new Foo);// => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
_.toPairsIn(object)
為 object
建立一個由自身和繼承的可列舉字串鍵值對陣列,可供 _.fromPairs
使用。如果 object
是 map 或 set,則傳回其項目。
4.0.0
_.entriesIn
object
(物件):要查詢的物件。(陣列):傳回鍵值對。
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.toPairsIn(new Foo);// => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
_.transform(object, [iteratee=_.identity], [accumulator])
替代 _.reduce
的方法;此方法將 object
轉換為新的 accumulator
物件,此物件是執行其每個可列舉字串鍵值屬性透過 iteratee
的結果,每次呼叫都可能變異 accumulator
物件。如果未提供 accumulator
,將使用具有相同 [[Prototype]]
的新物件。iteratee 會使用四個引數呼叫:(accumulator, value, key, object)。iteratee 函式可以透過明確傳回 false
來提早結束迭代。
1.3.0
object
(Object):要迭代的物件。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。[accumulator]
(*):自訂的累加器值。(*):傳回累積值。
_.transform([2, 3, 4], function(result, n) { result.push(n *= n); return n % 2 == 0;}, []);// => [4, 9] _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { (result[value] || (result[value] = [])).push(key);}, {});// => { '1': ['a', 'c'], '2': ['b'] }
_.unset(object, path)
移除 object
中 path
的屬性。
注意:此方法會改變 object
。
4.0.0
object
(物件):要修改的物件。path
(Array|string):要取消設定的屬性路徑。(boolean):如果已刪除屬性,傳回 true
,否則傳回 false
。
var object = { 'a': [{ 'b': { 'c': 7 } }] };_.unset(object, 'a[0].b.c');// => true console.log(object);// => { 'a': [{ 'b': {} }] }; _.unset(object, ['a', '0', 'b', 'c']);// => true console.log(object);// => { 'a': [{ 'b': {} }] };
_.update(object, path, updater)
此方法類似 _.set
,但接受 updater
來產生要設定的值。使用 _.updateWith
來自訂 path
建立。updater 會使用一個引數呼叫:(value)。
注意:此方法會改變 object
。
4.6.0
object
(物件):要修改的物件。path
(陣列|字串):要設定的屬性路徑。updater
(Function):產生更新值的函式。(Object):傳回 object
。
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.update(object, 'a[0].b.c', function(n) { return n * n; });console.log(object.a[0].b.c);// => 9 _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });console.log(object.x[0].y.z);// => 0
_.updateWith(object, path, updater, [customizer])
此方法類似於 _.update
,但它接受 customizer
,而 customizer
會被呼叫來產生 path
的物件。如果 customizer
傳回 undefined
,則路徑建立將由方法處理。customizer
會使用三個參數呼叫:(nsValue, key, nsObject)。
注意:此方法會改變 object
。
4.6.0
object
(物件):要修改的物件。path
(陣列|字串):要設定的屬性路徑。updater
(Function):產生更新值的函式。[customizer]
(Function):自訂指定值的函式。(Object):傳回 object
。
var object = {}; _.updateWith(object, '[0][1]', _.constant('a'), Object);// => { '0': { '1': 'a' } }
「Seq」方法
_(value)
建立一個 lodash
物件,它會包裝 value
以啟用隱式方法鏈序列。作用於陣列、集合和函式並傳回它們的方法可以鏈結在一起。擷取單一值或可能傳回原始值的方法會自動結束鏈序列並傳回未包裝的值。否則,必須使用 _#value
來解開該值。
必須使用 _#value
進行解開的明確鏈序列,可以使用 _.chain
啟用。
鏈結方法的執行是延遲的,也就是說,它會延遲到 _#value
被隱含或明確呼叫為止。
延遲評估允許多個方法支援捷徑融合。捷徑融合是一種最佳化,用於合併迭代器呼叫;這可以避免建立中間陣列,並且可以大幅減少迭代器執行的次數。鏈序列的區段符合捷徑融合的條件,如果該區段套用至陣列,且迭代器只接受一個參數。區段是否符合捷徑融合的條件,其啟發法可能會變更。
只要 _#value
方法直接或間接包含在建置中,鏈結便會在自訂建置中受到支援。
除了 lodash 方法之外,包裝器還有 Array
和 String
方法。
包裝器 Array
方法為concat
、join
、pop
、push
、shift
、sort
、splice
和 unshift
包裝器 String
方法為replace
和 split
支援捷徑融合的包裝器方法為at
、compact
、drop
、dropRight
、dropWhile
、filter
、find
、findLast
、head
、initial
、last
、map
、reject
、reverse
、slice
、tail
、take
、takeRight
、takeRightWhile
、takeWhile
和 toArray
可鏈接的包裝方法為after
, ary
, assign
, assignIn
, assignInWith
, assignWith
, at
, before
, bind
, bindAll
, bindKey
, castArray
, chain
, chunk
, commit
, compact
, concat
, conforms
, constant
, countBy
, create
, curry
, debounce
, defaults
, defaultsDeep
, defer
, delay
, difference
, differenceBy
, differenceWith
, drop
, dropRight
, dropRightWhile
, dropWhile
, extend
, extendWith
, fill
, filter
, flatMap
, flatMapDeep
, flatMapDepth
, flatten
, flattenDeep
, flattenDepth
, flip
, flow
, flowRight
, fromPairs
, functions
, functionsIn
, groupBy
, initial
, intersection
, intersectionBy
, intersectionWith
, invert
, invertBy
, invokeMap
, iteratee
, keyBy
, keys
, keysIn
, map
, mapKeys
, mapValues
, matches
, matchesProperty
, memoize
, merge
, mergeWith
, method
, methodOf
, mixin
, negate
, nthArg
, omit
, omitBy
, once
, orderBy
, over
, overArgs
, overEvery
, overSome
, partial
, partialRight
, partition
, pick
, pickBy
, plant
, property
, propertyOf
, pull
, pullAll
, pullAllBy
, pullAllWith
, pullAt
, push
, range
, rangeRight
, rearg
, reject
, remove
, rest
, reverse
, sampleSize
, set
, setWith
, shuffle
, slice
, sort
, sortBy
, splice
, spread
, tail
, take
, takeRight
, takeRightWhile
, takeWhile
, tap
, throttle
, thru
, toArray
, toPairs
, toPairsIn
, toPath
, toPlainObject
, transform
, unary
, union
, unionBy
, unionWith
, uniq
, uniqBy
, uniqWith
, unset
, unshift
, unzip
, unzipWith
, update
, updateWith
, values
, valuesIn
, without
, wrap
, xor
, xorBy
, xorWith
, zip
, zipObject
, zipObjectDeep
, and zipWith
預設不可鏈接的包裝方法為add
, attempt
, camelCase
, capitalize
, ceil
, clamp
, clone
, cloneDeep
, cloneDeepWith
, cloneWith
, conformsTo
, deburr
, defaultTo
, divide
, each
, eachRight
, endsWith
, eq
, escape
, escapeRegExp
, every
, find
, findIndex
, findKey
, findLast
, findLastIndex
, findLastKey
, first
, floor
, forEach
, forEachRight
, forIn
, forInRight
, forOwn
, forOwnRight
, get
, gt
, gte
, has
, hasIn
, head
, identity
, includes
, indexOf
, inRange
, invoke
, isArguments
, isArray
, isArrayBuffer
, isArrayLike
, isArrayLikeObject
, isBoolean
, isBuffer
, isDate
, isElement
, isEmpty
, isEqual
, isEqualWith
, isError
, isFinite
, isFunction
, isInteger
, isLength
, isMap
, isMatch
, isMatchWith
, isNaN
, isNative
, isNil
, isNull
, isNumber
, isObject
, isObjectLike
, isPlainObject
, isRegExp
, isSafeInteger
, isSet
, isString
, isUndefined
, isTypedArray
, isWeakMap
, isWeakSet
, join
, kebabCase
, last
, lastIndexOf
, lowerCase
, lowerFirst
, lt
, lte
, max
, maxBy
, mean
, meanBy
, min
, minBy
, multiply
, noConflict
, noop
, now
, nth
, pad
, padEnd
, padStart
, parseInt
, pop
, random
, reduce
, reduceRight
, repeat
, result
, round
, runInContext
, sample
, shift
, size
, snakeCase
, some
, sortedIndex
, sortedIndexBy
, sortedLastIndex
, sortedLastIndexBy
, startCase
, startsWith
, stubArray
, stubFalse
, stubObject
, stubString
, stubTrue
, subtract
, sum
, sumBy
, template
, times
, toFinite
, toInteger
, toJSON
, toLength
, toLower
, toNumber
, toSafeInteger
, toString
, toUpper
, trim
, trimEnd
, trimStart
, truncate
, unescape
, uniqueId
, upperCase
, upperFirst
, value
, and words
value
(*):要包裝在 lodash
實例中的值。(Object):傳回新的 lodash
包裝實例。
function square(n) { return n * n;} var wrapped = _([1, 2, 3]); // Returns an unwrapped value.wrapped.reduce(_.add);// => 6 // Returns a wrapped value.var squares = wrapped.map(square); _.isArray(squares);// => false _.isArray(squares.value());// => true
_.chain(value)
建立一個 lodash
包裝實例,包裝 value
並啟用明確的方法鏈序列。此類序列的結果必須使用 _#value
解開包裝。
1.3.0
value
(*): 要包裝的值。(Object):傳回新的 lodash
包裝實例。
var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'pebbles', 'age': 1 }]; var youngest = _ .chain(users) .sortBy('age') .map(function(o) { return o.user + ' is ' + o.age; }) .head() .value();// => 'pebbles is 1'
_.tap(value, interceptor)
此方法會呼叫 interceptor
並傳回 value
。interceptor 會使用一個引數呼叫;(value)。此方法的目的是「介入」方法鏈序列,以修改中間結果。
0.1.0
value
(*):要提供給 interceptor
的值。interceptor
(Function):要呼叫的函式。(*):傳回 value
。
_([1, 2, 3]) .tap(function(array) {// Mutate input array. array.pop(); }) .reverse() .value();// => [2, 1]
_.thru(value, interceptor)
此方法類似於 _.tap
,但它會傳回 interceptor
的結果。此方法的目的是「傳遞」值,取代方法鏈序列中的中間結果。
3.0.0
value
(*):要提供給 interceptor
的值。interceptor
(Function):要呼叫的函式。(*):傳回 interceptor
的結果。
_(' abc ') .chain() .trim() .thru(function(value) { return [value]; }) .value();// => ['abc']
_.prototype[Symbol.iterator]()
啟用包裝的迭代。
4.0.0
(Object):傳回包裝物件。
var wrapped = _([1, 2]); wrapped[Symbol.iterator]() === wrapped;// => true Array.from(wrapped);// => [1, 2]
_.prototype.at([paths])
此方法是 _.at
的包裝器版本。
1.0.0
[paths]
(...(string|string[])):要挑選的屬性路徑。(Object):傳回新的 lodash
包裝實例。
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; _(object).at(['a[0].b.c', 'a[1]']).value();// => [3, 4]
_.prototype.chain()
建立一個已啟用明確方法鏈序列的 lodash
包裝器實例。
0.1.0
(Object):傳回新的 lodash
包裝實例。
var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; // A sequence without explicit chaining._(users).head();// => { 'user': 'barney', 'age': 36 } // A sequence with explicit chaining._(users) .chain() .head() .pick('user') .value();// => { 'user': 'barney' }
_.prototype.commit()
執行鏈序列並傳回包裝好的結果。
3.2.0
(Object):傳回新的 lodash
包裝實例。
var array = [1, 2];var wrapped = _(array).push(3); console.log(array);// => [1, 2] wrapped = wrapped.commit();console.log(array);// => [1, 2, 3] wrapped.last();// => 3 console.log(array);// => [1, 2, 3]
_.prototype.next()
根據 迭代器協定 取得包裝物件上的下一個值。
4.0.0
(物件):傳回下一個迭代器值。
var wrapped = _([1, 2]); wrapped.next();// => { 'done': false, 'value': 1 } wrapped.next();// => { 'done': false, 'value': 2 } wrapped.next();// => { 'done': true, 'value': undefined }
_.prototype.plant(value)
建立鏈序列的複製,並將 value
植入為包裝值。
3.2.0
value
(*):要植入的值。(Object):傳回新的 lodash
包裝實例。
function square(n) { return n * n;} var wrapped = _([1, 2]).map(square);var other = wrapped.plant([3, 4]); other.value();// => [9, 16] wrapped.value();// => [1, 4]
_.prototype.reverse()
此方法是 _.reverse
的包裝器版本。
注意:此方法會改變包裝陣列。
0.1.0
(Object):傳回新的 lodash
包裝實例。
var array = [1, 2, 3]; _(array).reverse().value()// => [3, 2, 1] console.log(array);// => [3, 2, 1]
「字串」方法
_.camelCase([string=''])
將 string
轉換為 駝峰式大小寫。
3.0.0
[string='']
(字串):要轉換的字串。(字串):傳回駝峰式大小寫的字串。
_.camelCase('Foo Bar');// => 'fooBar' _.camelCase('--foo-bar--');// => 'fooBar' _.camelCase('__FOO_BAR__');// => 'fooBar'
_.capitalize([string=''])
將 string
的第一個字元轉換成大寫,其餘轉換成小寫。
3.0.0
[string='']
(字串): 要轉換大小寫的字串。(字串): 傳回轉換大小寫後的字串。
_.capitalize('FRED');// => 'Fred'
_.deburr([string=''])
將 string
中的 拉丁文補充 和 拉丁文擴充 A 字母轉換成基本拉丁字母,並移除 結合變音符號。
3.0.0
[string='']
(字串): 要移除變音符號的字串。(字串): 傳回移除變音符號後的字串。
_.deburr('déjà vu');// => 'deja vu'
_.endsWith([string=''], [target], [position=string.length])
檢查 string
是否以給定的目標字串結尾。
3.0.0
[string='']
(字串): 要檢查的字串。[target]
(字串): 要搜尋的字串。[position=string.length]
(數字): 要搜尋到的位置。(布林值):如果 string
以 target
結尾,則傳回 true
,否則傳回 false
。
_.endsWith('abc', 'c');// => true _.endsWith('abc', 'b');// => false _.endsWith('abc', 'b', 2);// => true
_.escape([string=''])
將 string
中的字元 "&", "<", ">", '"', 和 "'" 轉換為對應的 HTML 實體。
注意:不會轉換其他字元。若要轉換其他字元,請使用第三方函式庫,例如 he。
雖然 ">" 字元會為了對稱性而轉換,但 ">" 和 "/" 等字元在 HTML 中不需要轉換,除非它們是標籤或未加引號的屬性值的一部分,否則沒有特殊意義。請參閱 Mathias Bynens 的文章 (在「半相關的有趣事實」之下) 以取得更多詳細資訊。
使用 HTML 時,您應該總是 加上屬性值的引號 以減少 XSS 向量。
0.1.0
[string='']
(字串):要轉換的字串。(字串):傳回轉換後的字串。
_.escape('fred, barney, & pebbles');// => 'fred, barney, & pebbles'
_.escapeRegExp([string=''])
在 string
中跳脫 RegExp
特殊字元 "^", "$", "", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", 和 "|".
3.0.0
[string='']
(字串):要轉換的字串。(字串):傳回轉換後的字串。
_.escapeRegExp('[lodash](https://lodash.dev.org.tw/)');// => '\[lodash\]\(https://lodash\.com/\)'
_.kebabCase([string=''])
將 string
轉換成 kebab case。
3.0.0
[string='']
(字串):要轉換的字串。(字串): 傳回 kebab case 字串。
_.kebabCase('Foo Bar');// => 'foo-bar' _.kebabCase('fooBar');// => 'foo-bar' _.kebabCase('__FOO_BAR__');// => 'foo-bar'
_.lowerCase([string=''])
將 string
轉換成小寫,並以空格分隔字詞。
4.0.0
[string='']
(字串):要轉換的字串。(字串): 傳回小寫字串。
_.lowerCase('--Foo-Bar--');// => 'foo bar' _.lowerCase('fooBar');// => 'foo bar' _.lowerCase('__FOO_BAR__');// => 'foo bar'
_.lowerFirst([string=''])
將 string
的第一個字元轉換成小寫。
4.0.0
[string='']
(字串):要轉換的字串。(字串): 傳回轉換後的字串。
_.lowerFirst('Fred');// => 'fred' _.lowerFirst('FRED');// => 'fRED'
_.pad([string=''], [length=0], [chars=' '])
如果 string
比 length
短,則在 string
的左右兩側填補字元。如果填補字元無法平均除以 length
,則會將其截斷。
3.0.0
[string='']
(字串): 要填補的字串。[length=0]
(數字): 填補長度。[chars=' ']
(字串): 用於填補的字串。(字串):傳回已填補的字串。
_.pad('abc', 8);// => ' abc ' _.pad('abc', 8, '_-');// => '_-abc_-_' _.pad('abc', 3);// => 'abc'
_.padEnd([string=''], [length=0], [chars=' '])
如果 string
比 length
短,則在 string
的右側填補。如果填補字元超過 length
,則會將其截斷。
4.0.0
[string='']
(字串): 要填補的字串。[length=0]
(數字): 填補長度。[chars=' ']
(字串): 用於填補的字串。(字串):傳回已填補的字串。
_.padEnd('abc', 6);// => 'abc ' _.padEnd('abc', 6, '_-');// => 'abc_-_' _.padEnd('abc', 3);// => 'abc'
_.padStart([string=''], [length=0], [chars=' '])
如果 string
比 length
短,則在 string
的左側填補。如果填補字元超過 length
,則會將其截斷。
4.0.0
[string='']
(字串): 要填補的字串。[length=0]
(數字): 填補長度。[chars=' ']
(字串): 用於填補的字串。(字串):傳回已填補的字串。
_.padStart('abc', 6);// => ' abc' _.padStart('abc', 6, '_-');// => '_-_abc' _.padStart('abc', 3);// => 'abc'
_.parseInt(string, [radix=10])
將 string
轉換為指定進制的整數。如果 radix
為 undefined
或 0
,則使用進制 10
,除非 value
為十六進制,則使用進制 16
。
注意:此方法與 ES5 實作 的 parseInt
相符。
1.1.0
string
(字串):要轉換的字串。[radix=10]
(數字):用於詮釋 value
的進制。(數字):傳回轉換後的整數。
_.parseInt('08');// => 8 _.map(['6', '08', '10'], _.parseInt);// => [6, 8, 10]
_.repeat([string=''], [n=1])
重複給定的字串 n
次。
3.0.0
[string='']
(字串):要重複的字串。[n=1]
(數字):重複字串的次數。(字串):傳回重複的字串。
_.repeat('*', 3);// => '***' _.repeat('abc', 2);// => 'abcabc' _.repeat('abc', 0);// => ''
_.replace([string=''], pattern, replacement)
用 replacement
取代 string
中符合 pattern
的部分。
注意: 此方法是根據 String#replace
建立的。
4.0.0
[string='']
(字串):要修改的字串。pattern
(RegExp|字串):要取代的樣式。replacement
(函式|字串):符合項目的取代字串。(字串):傳回修改後的字串。
_.replace('Hi Fred', 'Fred', 'Barney');// => 'Hi Barney'
_.snakeCase([string=''])
將 string
轉換為 蛇形大小寫。
3.0.0
[string='']
(字串):要轉換的字串。(字串):傳回蛇形大小寫的字串。
_.snakeCase('Foo Bar');// => 'foo_bar' _.snakeCase('fooBar');// => 'foo_bar' _.snakeCase('--FOO-BAR--');// => 'foo_bar'
_.split([string=''], separator, [limit])
以 separator
分割 string
。
注意: 此方法是根據 String#split
建立的。
4.0.0
[string='']
(字串):要分割的字串。separator
(RegExp|字串):依據其來分割的分隔符號樣式。[limit]
(數字):將結果截斷的長度。(陣列):傳回字串區段。
_.split('a-b-c', '-', 2);// => ['a', 'b']
_.startCase([字串=''])
將 字串
轉換為 首字母大寫。
3.1.0
[string='']
(字串):要轉換的字串。(字串):傳回首字母大寫的字串。
_.startCase('--foo-bar--');// => 'Foo Bar' _.startCase('fooBar');// => 'Foo Bar' _.startCase('__FOO_BAR__');// => 'FOO BAR'
_.startsWith([字串=''], [目標], [位置=0])
檢查 字串
是否以給定的目標字串開頭。
3.0.0
[string='']
(字串): 要檢查的字串。[target]
(字串): 要搜尋的字串。[位置=0]
(數字):開始搜尋的位置。(布林值):如果 字串
以 目標
開頭,傳回 true
,否則傳回 false
。
_.startsWith('abc', 'a');// => true _.startsWith('abc', 'b');// => false _.startsWith('abc', 'b', 1);// => true
_.template([字串=''], [選項={}])
建立一個編譯好的範本函式,它可以在「內插」分隔符號中內插資料屬性,在「跳脫」分隔符號中 HTML 跳脫內插的資料屬性,並在「評估」分隔符號中執行 JavaScript。資料屬性可以在範本中作為自由變數存取。如果給定設定物件,它會優先於 _.templateSettings
值。
注意:在開發版本中,_.template
使用 sourceURL 以利除錯。
有關預編譯範本的更多資訊,請參閱 lodash 的自訂版本文件。
有關 Chrome 擴充功能沙盒的更多資訊,請參閱 Chrome 的擴充功能文件。
0.1.0
[string='']
(字串):範本字串。[options={}]
(物件):選項物件。[options.escape=_.templateSettings.escape]
(正規表示法):HTML「escape」分隔符。[options.evaluate=_.templateSettings.evaluate]
(正規表示法):「evaluate」分隔符。[options.imports=_.templateSettings.imports]
(物件):要作為自由變數匯入範本的物件。[options.interpolate=_.templateSettings.interpolate]
(正規表示法):「interpolate」分隔符。[options.sourceURL='lodash.templateSources[n]']
(字串):已編譯範本的 sourceURL。[options.variable='obj']
(字串):資料物件變數名稱。(函式):傳回已編譯的範本函式。
// Use the "interpolate" delimiter to create a compiled template.var compiled = _.template('hello <%= user %>!');compiled({ 'user': 'fred' });// => 'hello fred!' // Use the HTML "escape" delimiter to escape data property values.var compiled = _.template('<b><%- value %></b>');compiled({ 'value': '<script>' });// => '<b><script></b>' // Use the "evaluate" delimiter to execute JavaScript and generate HTML.var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');compiled({ 'users': ['fred', 'barney'] });// => '<li>fred</li><li>barney</li>' // Use the internal `print` function in "evaluate" delimiters.var compiled = _.template('<% print("hello " + user); %>!');compiled({ 'user': 'barney' });// => 'hello barney!' // Use the ES template literal delimiter as an "interpolate" delimiter.// Disable support by replacing the "interpolate" delimiter.var compiled = _.template('hello ${ user }!');compiled({ 'user': 'pebbles' });// => 'hello pebbles!' // Use backslashes to treat delimiters as plain text.var compiled = _.template('<%= "\\<%- value %\\>" %>');compiled({ 'value': 'ignored' });// => '<%- value %>' // Use the `imports` option to import `jQuery` as `jq`.var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';var compiled = _.template(text, { 'imports': { 'jq': jQuery } });compiled({ 'users': ['fred', 'barney'] });// => '<li>fred</li><li>barney</li>' // Use the `sourceURL` option to specify a custom sourceURL for the template.var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });compiled(data);// => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. // Use the `variable` option to ensure a with-statement isn't used in the compiled template.var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });compiled.source;// => function(data) {// var __t, __p = '';// __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';// return __p;// } // Use custom template delimiters._.templateSettings.interpolate = /{{([\s\S]+?)}}/g;var compiled = _.template('hello {{ user }}!');compiled({ 'user': 'mustache' });// => 'hello mustache!' // Use the `source` property to inline compiled templates for meaningful// line numbers in error messages and stack traces.fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ var JST = {\ "main": ' + _.template(mainText).source + '\ };\');
_.toLower([string=''])
將整個 string
轉換為小寫,就像 String#toLowerCase 一樣。
4.0.0
[string='']
(字串):要轉換的字串。(字串): 傳回小寫字串。
_.toLower('--Foo-Bar--');// => '--foo-bar--' _.toLower('fooBar');// => 'foobar' _.toLower('__FOO_BAR__');// => '__foo_bar__'
_.toUpper([string=''])
將整個 string
轉換為大寫,就像 String#toUpperCase 一樣。
4.0.0
[string='']
(字串):要轉換的字串。(字串):傳回大寫的字串。
_.toUpper('--foo-bar--');// => '--FOO-BAR--' _.toUpper('fooBar');// => 'FOOBAR' _.toUpper('__foo_bar__');// => '__FOO_BAR__'
_.trim([string=''], [chars=whitespace])
移除 `string` 中開頭和結尾的空白或指定字元。
3.0.0
[string='']
(字串): 要修剪的字串。[chars=whitespace]
(字串): 要修剪的字元。(字串): 傳回修剪後的字串。
_.trim(' abc ');// => 'abc' _.trim('-_-abc-_-', '_-');// => 'abc' _.map([' foo ', ' bar '], _.trim);// => ['foo', 'bar']
_.trimEnd([string=''], [chars=whitespace])
移除 `string` 中結尾的空白或指定字元。
4.0.0
[string='']
(字串): 要修剪的字串。[chars=whitespace]
(字串): 要修剪的字元。(字串): 傳回修剪後的字串。
_.trimEnd(' abc ');// => ' abc' _.trimEnd('-_-abc-_-', '_-');// => '-_-abc'
_.trimStart([string=''], [chars=whitespace])
移除 `string` 中開頭的空白或指定字元。
4.0.0
[string='']
(字串): 要修剪的字串。[chars=whitespace]
(字串): 要修剪的字元。(字串): 傳回修剪後的字串。
_.trimStart(' abc ');// => 'abc ' _.trimStart('-_-abc-_-', '_-');// => 'abc-_-'
_.truncate([string=''], [options={}])
如果 `string` 超過給定的最大字串長度,則會將其截斷。截斷字串的最後幾個字元會被省略字串取代,其預設值為「...」。
4.0.0
[string='']
(字串): 要截斷的字串。[options={}]
(物件):選項物件。[options.length=30]
(數字): 最大字串長度。[options.omission='...']
(字串): 表示文字已省略的字串。[options.separator]
(RegExp|字串): 要截斷的分隔符號樣式。(字串): 傳回截斷後的字串。
_.truncate('hi-diddly-ho there, neighborino');// => 'hi-diddly-ho there, neighbo...' _.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' '});// => 'hi-diddly-ho there,...' _.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/});// => 'hi-diddly-ho there...' _.truncate('hi-diddly-ho there, neighborino', { 'omission': ' [...]'});// => 'hi-diddly-ho there, neig [...]'
_.unescape([string=''])
_.escape
的反函數;此函數會將 string
中的 HTML 實體 &
、<
、>
、"
和 '
轉換成對應的字元。
注意:不會將其他 HTML 實體轉換回來。若要轉換其他 HTML 實體,請使用第三方函式庫,例如 he。
0.6.0
[string='']
(字串):要轉換的字串。(字串):傳回已轉換的字串。
_.unescape('fred, barney, & pebbles');// => 'fred, barney, & pebbles'
_.upperCase([string=''])
將 string
(以空白分隔的字詞)轉換成大寫。
4.0.0
[string='']
(字串):要轉換的字串。(字串):傳回大寫的字串。
_.upperCase('--foo-bar');// => 'FOO BAR' _.upperCase('fooBar');// => 'FOO BAR' _.upperCase('__foo_bar__');// => 'FOO BAR'
_.upperFirst([string=''])
將 string
的第一個字元轉換成大寫。
4.0.0
[string='']
(字串):要轉換的字串。(字串): 傳回轉換後的字串。
_.upperFirst('fred');// => 'Fred' _.upperFirst('FRED');// => 'FRED'
_.words([string=''], [pattern])
將 string
拆分為一個陣列,其中包含字詞。
3.0.0
[string='']
(字串): 要檢查的字串。[pattern]
(RegExp|字串):用於比對字詞的樣式。(陣列):傳回 string
的字詞。
_.words('fred, barney, & pebbles');// => ['fred', 'barney', 'pebbles'] _.words('fred, barney, & pebbles', /[^, ]+/g);// => ['fred', 'barney', '&', 'pebbles']
「實用程式」函數
_.attempt(func, [args])
嘗試呼叫 func
,傳回結果或捕捉到的錯誤物件。呼叫 func
時,會提供任何其他引數。
3.0.0
func
(函式):要嘗試的函式。[args]
(...*):呼叫 func
時要使用的引數。(*):傳回 func
結果或錯誤物件。
// Avoid throwing errors for invalid selectors.var elements = _.attempt(function(selector) { return document.querySelectorAll(selector);}, '>_>'); if (_.isError(elements)) { elements = [];}
_.bindAll(object, methodNames)
將物件的方法繫結到物件本身,覆寫現有方法。
注意:此方法不會設定繫結函式的「length」屬性。
0.1.0
object
(物件):要繫結並指派繫結方法的物件。methodNames
(...(字串|字串陣列)):要繫結的物件方法名稱。(Object):傳回 object
。
var view = { 'label': 'docs', 'click': function() { console.log('clicked ' + this.label); }}; _.bindAll(view, ['click']);jQuery(element).on('click', view.click);// => Logs 'clicked docs' when clicked.
_.cond(pairs)
建立一個函式,會反覆運算 pairs
並呼叫第一個回傳真值的謂詞函式。謂詞函式配對會使用建立函式的 this
繫結和引數呼叫。
4.0.0
pairs
(陣列):謂詞函式配對。(函式):傳回新的複合函式。
var func = _.cond([ [_.matches({ 'a': 1 }), _.constant('matches A')], [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], [_.stubTrue, _.constant('no match')]]); func({ 'a': 1, 'b': 2 });// => 'matches A' func({ 'a': 0, 'b': 1 });// => 'matches B' func({ 'a': '1', 'b': '2' });// => 'no match'
_.conforms(source)
建立一個函式,呼叫 source
的謂詞屬性,並傳入給定物件的對應屬性值,如果所有謂詞都傳回真值,則傳回 true
,否則傳回 false
。
注意:建立的函式等同於已部分套用 source
的 _.conformsTo
。
4.0.0
source
(Object):要符合的屬性謂詞物件。(函式):傳回新的規格函式。
var objects = [ { 'a': 2, 'b': 1 }, { 'a': 1, 'b': 2 }]; _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));// => [{ 'a': 1, 'b': 2 }]
_.constant(value)
建立一個傳回 value
的函式。
2.4.0
value
(*):要從新函式傳回的值。(函式):傳回新的常數函式。
var objects = _.times(2, _.constant({ 'a': 1 })); console.log(objects);// => [{ 'a': 1 }, { 'a': 1 }] console.log(objects[0] === objects[1]);// => true
_.defaultTo(value, defaultValue)
檢查 value
以確定是否應傳回預設值來取代它。如果 value
為 NaN
、null
或 undefined
,則傳回 defaultValue
。
4.14.0
value
(*):要檢查的值。defaultValue
(*):預設值。(*):傳回解析出的值。
_.defaultTo(1, 10);// => 1 _.defaultTo(undefined, 10);// => 10
_.flow([funcs])
建立一個函數,傳回呼叫給定函數的結果,使用建立函數的 this
繫結,其中每個後續呼叫都提供前一個呼叫的傳回值。
3.0.0
[funcs]
(...(Function|Function[])):要呼叫的函數。(函式):傳回新的複合函式。
function square(n) { return n * n;} var addSquare = _.flow([_.add, square]);addSquare(1, 2);// => 9
_.flowRight([funcs])
此方法類似於 _.flow
,但它建立一個函數,從右到左呼叫給定的函數。
3.0.0
[funcs]
(...(Function|Function[])):要呼叫的函數。(函式):傳回新的複合函式。
function square(n) { return n * n;} var addSquare = _.flowRight([square, _.add]);addSquare(1, 2);// => 9
_.identity(value)
此方法傳回它接收到的第一個參數。
0.1.0
value
(*):任何值。(*):傳回 value
。
var object = { 'a': 1 }; console.log(_.identity(object) === object);// => true
_.iteratee([func=_.identity])
建立一個函數,使用建立函數的參數呼叫 func
。如果 func
是屬性名稱,建立的函數傳回給定元素的屬性值。如果 func
是陣列或物件,建立的函數傳回 true
給包含等效來源屬性的元素,否則傳回 false
。
4.0.0
[func=_.identity]
(*):要轉換為回呼的值。(函數):傳回回呼。
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; // The `_.matches` iteratee shorthand._.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));// => [{ 'user': 'barney', 'age': 36, 'active': true }] // The `_.matchesProperty` iteratee shorthand._.filter(users, _.iteratee(['user', 'fred']));// => [{ 'user': 'fred', 'age': 40 }] // The `_.property` iteratee shorthand._.map(users, _.iteratee('user'));// => ['barney', 'fred'] // Create custom iteratee shorthands._.iteratee = _.wrap(_.iteratee, function(iteratee, func) { return !_.isRegExp(func) ? iteratee(func) : function(string) { return func.test(string); };}); _.filter(['abc', 'def'], /ef/);// => ['def']
_.matches(source)
建立一個函數,在給定的物件和 source
之間執行部分深度比較,如果給定的物件具有等效的屬性值,則傳回 true
,否則傳回 false
。
注意:建立的函數等同於 source
部分套用的 _.isMatch
。
部分比較會將空的陣列和空的物件 source
值分別與任何陣列或物件值相符。請參閱 _.isEqual
以取得支援的值比較清單。
3.0.0
source
(物件):要比對屬性值的物件。(函式):傳回新的規格函式。
var objects = [ { 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]; _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));// => [{ 'a': 4, 'b': 5, 'c': 6 }]
_.matchesProperty(path, srcValue)
建立一個函數,在給定物件的 path
處的值和 srcValue
之間執行部分深度比較,如果物件值相等,則傳回 true
,否則傳回 false
。
注意:部分比較會將空的陣列和空的物件 srcValue
值分別與任何陣列或物件值進行比對。請參閱 _.isEqual
以取得支援的值比較清單。
3.2.0
path
(陣列或字串):要取得屬性的路徑。srcValue
(*):要比對的值。(函式):傳回新的規格函式。
var objects = [ { 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]; _.find(objects, _.matchesProperty('a', 4));// => { 'a': 4, 'b': 5, 'c': 6 }
_.method(path, [args])
建立一個函數,呼叫給定物件 path
處的方法。任何其他引數都會提供給呼叫的方法。
3.7.0
path
(Array|string): 要呼叫的方法路徑。[args]
(...*): 要呼叫方法的引數。(函數):傳回新的呼叫函數。
var objects = [ { 'a': { 'b': _.constant(2) } }, { 'a': { 'b': _.constant(1) } }]; _.map(objects, _.method('a.b'));// => [2, 1] _.map(objects, _.method(['a', 'b']));// => [2, 1]
_.methodOf(object, [args])
_.method
的相反函式;此函式會建立一個函式,用來呼叫 `object` 指定路徑的方法。任何額外的參數都會提供給呼叫的方法。
3.7.0
object
(物件):要查詢的物件。[args]
(...*): 要呼叫方法的引數。(函數):傳回新的呼叫函數。
var array = _.times(3, _.constant), object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.methodOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.methodOf(object));// => [2, 0]
_.mixin([object=lodash], source, [options={}])
將來源物件的所有可列舉字串金鑰函式屬性加入目標物件。如果 `object` 是函式,則也會將方法加入其原型。
注意:使用 _.runInContext
建立一個原始的 `lodash` 函式,以避免修改原始函式所造成的衝突。
0.1.0
[object=lodash]
(函式|物件):目標物件。source
(物件):要加入函式的物件。[options={}]
(物件):選項物件。[options.chain=true]
(布林值):指定混入是否可串接。(*):傳回 `object`。
function vowels(string) { return _.filter(string, function(v) { return /[aeiou]/i.test(v); });} _.mixin({ 'vowels': vowels });_.vowels('fred');// => ['e'] _('fred').vowels().value();// => ['e'] _.mixin({ 'vowels': vowels }, { 'chain': false });_('fred').vowels();// => ['e']
_.noConflict()
將 `_` 變數還原為其先前的值,並傳回對 `lodash` 函式的參考。
0.1.0
(函式):傳回 `lodash` 函式。
var lodash = _.noConflict();
_.nthArg([n=0])
建立一個函式,取得索引值為 n
的參數。如果 n
為負數,則會傳回從最後開始算起的第 n 個參數。
4.0.0
[n=0]
(數字):要傳回的參數索引值。(函式):傳回新的直通函式。
var func = _.nthArg(1);func('a', 'b', 'c', 'd');// => 'b' var func = _.nthArg(-2);func('a', 'b', 'c', 'd');// => 'c'
_.over([iteratees=[_.identity]])
建立一個函式,使用接收到的參數呼叫 iteratees
,並傳回其結果。
4.0.0
[iteratees=[_.identity]]
(...(函式|函式陣列)):要呼叫的 iteratee。(Function): 傳回新的函式。
var func = _.over([Math.max, Math.min]); func(1, 2, 3, 4);// => [4, 1]
_.overEvery([predicates=[_.identity]])
建立一個函式,檢查當使用接收到的參數呼叫 所有 predicates
時,是否都會傳回真值。
4.0.0
[predicates=[_.identity]]
(...(函式|函式陣列)):要檢查的謂詞。(Function): 傳回新的函式。
var func = _.overEvery([Boolean, isFinite]); func('1');// => true func(null);// => false func(NaN);// => false
_.overSome([predicates=[_.identity]])
建立一個函式,檢查當使用接收到的引數呼叫 predicates
時,是否任何會傳回真值。
4.0.0
[predicates=[_.identity]]
(...(函式|函式陣列)):要檢查的謂詞。(Function): 傳回新的函式。
var func = _.overSome([Boolean, isFinite]); func('1');// => true func(null);// => true func(NaN);// => false
_.property(path)
建立一個函式,傳回給定物件的 path
處的值。
2.4.0
path
(陣列或字串):要取得屬性的路徑。(函式):傳回新的存取函式。
var objects = [ { 'a': { 'b': 2 } }, { 'a': { 'b': 1 } }]; _.map(objects, _.property('a.b'));// => [2, 1] _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');// => [1, 2]
_.propertyOf(object)
與 _.property
相反;此方法建立一個函式,傳回 object
給定路徑處的值。
3.0.0
object
(物件):要查詢的物件。(函式):傳回新的存取函式。
var array = [0, 1, 2], object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.propertyOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.propertyOf(object));// => [2, 0]
_.range([start=0], end, [step=1])
建立一個數字陣列(正數和/或負數),從 start
開始遞增到 end
,但不包含 end
。如果指定負 start
但沒有 end
或 step
,則使用步長 -1
。如果未指定 end
,則將其設定為 start
,然後將 start
設定為 0
。
注意: JavaScript 遵循 IEEE-754 標準來解析浮點數值,這可能會產生意外的結果。
0.1.0
[start=0]
(數字):範圍的開頭。end
(數字):範圍的結尾。[step=1]
(數字):增量或減量的值。(陣列):傳回數字範圍。
_.range(4);// => [0, 1, 2, 3] _.range(-4);// => [0, -1, -2, -3] _.range(1, 5);// => [1, 2, 3, 4] _.range(0, 20, 5);// => [0, 5, 10, 15] _.range(0, -4, -1);// => [0, -1, -2, -3] _.range(1, 4, 0);// => [1, 1, 1] _.range(0);// => []
_.rangeRight([start=0], end, [step=1])
此方法類似於 _.range
,但它會以遞減順序填入值。
4.0.0
[start=0]
(數字):範圍的開頭。end
(數字):範圍的結尾。[step=1]
(數字):增量或減量的值。(陣列):傳回數字範圍。
_.rangeRight(4);// => [3, 2, 1, 0] _.rangeRight(-4);// => [-3, -2, -1, 0] _.rangeRight(1, 5);// => [4, 3, 2, 1] _.rangeRight(0, 20, 5);// => [15, 10, 5, 0] _.rangeRight(0, -4, -1);// => [-3, -2, -1, 0] _.rangeRight(1, 4, 0);// => [1, 1, 1] _.rangeRight(0);// => []
_.runInContext([context=root])
使用 context
物件建立一個新的原始 lodash
函式。
1.1.0
[context=root]
(物件):context 物件。(函式):傳回一個新的 lodash
函式。
_.mixin({ 'foo': _.constant('foo') }); var lodash = _.runInContext();lodash.mixin({ 'bar': lodash.constant('bar') }); _.isFunction(_.foo);// => true_.isFunction(_.bar);// => false lodash.isFunction(lodash.foo);// => falselodash.isFunction(lodash.bar);// => true // Create a suped-up `defer` in Node.js.var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
_.stubArray()
此方法會傳回一個新的空陣列。
4.13.0
(陣列):傳回新的空陣列。
var arrays = _.times(2, _.stubArray); console.log(arrays);// => [[], []] console.log(arrays[0] === arrays[1]);// => false
_.stubObject()
此方法會傳回一個新的空物件。
4.13.0
(物件):傳回新的空物件。
var objects = _.times(2, _.stubObject); console.log(objects);// => [{}, {}] console.log(objects[0] === objects[1]);// => false
_.times(n, [iteratee=_.identity])
呼叫 n
次迭代函式,傳回每次呼叫的結果陣列。迭代函式會使用一個參數呼叫;(索引)。
0.1.0
n
(數字):呼叫 iteratee
的次數。[iteratee=_.identity]
(函式):每次反覆運算呼叫的函式。(陣列):傳回結果陣列。
_.times(3, String);// => ['0', '1', '2'] _.times(4, _.constant(0));// => [0, 0, 0, 0]
方法