本页内容
Sommatic 文档
打开控制台

lodash

表达式中可通过 _ 使用的全部 lodash 函数:数组、集合、对象、字符串等,版本与 Sommatic AI 实际运行的版本一致。

以 Markdown 查看
在以下应用中打开

版本 4.18.1 MIT 官方文档

在 {{ }} 中通过 _ 调用任意函数,可用于对前序节点的数据进行分组、过滤、选取与重组:

JavaScript
{{ _.groupBy($json.items, 'status') }}

Array

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

把数组按 size 长度拆分成若干组并返回新数组。若 array 无法均分,最后一组为剩余元素。

  • array Array 要处理的数组。
  • size number 可选 默认值 1 每组的长度。

→ Array

_.chunk(['a', 'b', 'c', 'd'], 2)
结果 list
[["a","b"],["c","d"]]
_.chunk(['a', 'b', 'c', 'd'], 3)
结果 list
[["a","b","c"],["d"]]

_.compact(array)

创建一个移除所有假值后的新数组。假值包括 false、null、0、-0、0n、""、undefined 和 NaN。

  • array Array 要压缩(剔除假值)的数组。

→ Array

_.compact([0, 1, false, 2, '', 3])
结果 list
[1,2,3]

_.concat(array, [values])

创建一个新数组,将 array 与任意数组和/或值连接起来。

  • array Array 要连接的数组。
  • values ...* 可选 要连接的值。

→ Array

var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other)
结果 undefined
undefined
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(array)
结果 undefined
undefined

_.difference(array, [values])

创建一个数组,包含 array 中不在其他给定数组里的值,使用 SameValueZero 判断相等。结果的顺序和引用由第一个数组决定。

注意: 与 _.pullAll 不同,此方法返回新数组。

  • array Array 要检查的数组。
  • values ...Array 可选 要排除的值。

→ Array

_.difference([2, 1], [2, 3])
结果 list
[1]

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

与 _.difference 类似,但接受一个 iteratee,对 array 和 values 的每个元素调用它以生成比较依据。结果的顺序和引用由第一个数组决定。iteratee 调用时传入一个参数:(value)。

注意: 与 _.pullAllBy 不同,此方法返回新数组。

  • array Array 要检查的数组。
  • values ...Array 可选 要排除的值。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Array

_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor)
结果 list
[1.2]
_.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x')
结果 list
[{"x":2}]

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

与 _.difference 类似,但接受一个 comparator 来比较 array 与 values 的元素。结果的顺序和引用由第一个数组决定。comparator 调用时传入两个参数:(arrVal, othVal)。

注意: 与 _.pullAllWith 不同,此方法返回新数组。

  • array Array 要检查的数组。
  • values ...Array 可选 要排除的值。
  • comparator Function 可选 对每个元素调用的比较函数(comparator)。

→ Array

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
_.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual)
结果 list
[{"x":2,"y":1}]

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

创建 array 的切片,从开头丢弃 n 个元素。

  • array Array 要查询的数组。
  • n number 可选 默认值 1 要丢弃的元素个数。

→ Array

_.drop([1, 2, 3])
结果 list
[2,3]
_.drop([1, 2, 3], 2)
结果 list
[3]
_.drop([1, 2, 3], 5)
结果 list
[]
_.drop([1, 2, 3], 0)
结果 list
[1,2,3]

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

创建 array 的切片,从末尾丢弃 n 个元素。

  • array Array 要查询的数组。
  • n number 可选 默认值 1 要丢弃的元素个数。

→ Array

_.dropRight([1, 2, 3])
结果 list
[1,2]
_.dropRight([1, 2, 3], 2)
结果 list
[1]
_.dropRight([1, 2, 3], 5)
结果 list
[]
_.dropRight([1, 2, 3], 0)
结果 list
[1,2,3]

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

创建 array 的切片,从末尾开始丢弃元素,直到 predicate 返回假值为止。predicate 调用时传入三个参数:(value, index, array)。

  • array Array 要查询的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(users, function(o) { return !o.active; })
结果 list
[{"user":"barney","active":true}]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(users, { 'user': 'pebbles', 'active': false })
结果 list
[{"user":"barney","active":true},{"user":"fred","active":false}]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(users, ['active', false])
结果 list
[{"user":"barney","active":true}]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(users, 'active')
结果 list
[
  {
    "user": "barney",
    "active": true
  },
  {
    "user": "fred",
    "active": false
  },
  {
    "user": "pebbles",
    "active": false
  }
]

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

创建 array 的切片,从开头开始丢弃元素,直到 predicate 返回假值为止。predicate 调用时传入三个参数:(value, index, array)。

  • array Array 要查询的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.dropWhile(users, function(o) { return !o.active; })
结果 list
[{"user":"pebbles","active":true}]
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.dropWhile(users, { 'user': 'barney', 'active': false })
结果 list
[{"user":"fred","active":false},{"user":"pebbles","active":true}]
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.dropWhile(users, ['active', false])
结果 list
[{"user":"pebbles","active":true}]
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.dropWhile(users, 'active')
结果 list
[
  {
    "user": "barney",
    "active": false
  },
  {
    "user": "fred",
    "active": false
  },
  {
    "user": "pebbles",
    "active": true
  }
]

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

用 value 填充 array 中从 start 到 end(不含)的元素。

注意: 此方法会修改 array。

  • array Array 要填充的数组。
  • value * 用于填充 `array` 的值。
  • start number 可选 默认值 0 起始位置。
  • end number 可选 默认值 array.length 结束位置。

→ Array

var array = [1, 2, 3];
console.log(array)
结果 undefined
undefined
var array = [1, 2, 3];
_.fill(Array(3), 2)
结果 list
[2,2,2]
var array = [1, 2, 3];
_.fill([4, 6, 8, 10], '*', 1, 3)
结果 list
[4,"*","*",10]

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

与 _.find 类似,但返回第一个使 predicate 返回真值的元素的索引,而不是元素本身。

  • array Array 要检查的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • fromIndex number 可选 默认值 0 开始查找的索引。

→ number

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.findIndex(users, function(o) { return o.user == 'barney'; })
结果 number
0
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.findIndex(users, { 'user': 'fred', 'active': false })
结果 number
1
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.findIndex(users, ['active', false])
结果 number
0
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.findIndex(users, 'active')
结果 number
2

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

与 _.findIndex 类似,但从右向左遍历 collection。

  • array Array 要检查的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • fromIndex number 可选 默认值 array.length-1 开始查找的索引。

→ number

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.findLastIndex(users, function(o) { return o.user == 'pebbles'; })
结果 number
2
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.findLastIndex(users, { 'user': 'barney', 'active': true })
结果 number
0
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.findLastIndex(users, ['active', false])
结果 number
2
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.findLastIndex(users, 'active')
结果 number
0

_.flatten(array)

将 array 展平一层。

  • array Array 要展平的数组。

→ Array

_.flatten([1, [2, [3, [4]], 5]])
结果 list
[1,2,[3,[4]],5]

_.flattenDeep(array)

递归展平 array。

  • array Array 要展平的数组。

→ Array

_.flattenDeep([1, [2, [3, [4]], 5]])
结果 list
[1,2,3,4,5]

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

将 array 递归展平最多 depth 层。

  • array Array 要展平的数组。
  • depth number 可选 默认值 1 最大递归深度。

→ Array

var array = [1, [2, [3, [4]], 5]];
_.flattenDepth(array, 1)
结果 list
[1,2,[3,[4]],5]
var array = [1, [2, [3, [4]], 5]];
_.flattenDepth(array, 2)
结果 list
[1,2,3,[4],5]

_.fromPairs(pairs)

_.toPairs 的逆操作:由键值对数组 pairs 构建并返回一个对象。

  • pairs Array 键值对数组。

→ Object

_.fromPairs([['a', 1], ['b', 2]])
结果 object
{"a":1,"b":2}

_.head(array)

获取 array 的第一个元素。

  • array Array 要查询的数组。

→ *

_.head([1, 2, 3])
结果 number
1
_.head([])
结果 undefined
undefined

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

使用 SameValueZero 判断相等,返回 value 在 array 中首次出现的索引。fromIndex 为负数时表示从 array 末尾倒数的偏移。

  • array Array 要检查的数组。
  • value * 要查找的值。
  • fromIndex number 可选 默认值 0 开始查找的索引。

→ number

_.indexOf([1, 2, 1, 2], 2)
结果 number
1
_.indexOf([1, 2, 1, 2], 2, 2)
结果 number
3

_.initial(array)

获取 array 除最后一个元素外的所有元素。

  • array Array 要查询的数组。

→ Array

_.initial([1, 2, 3])
结果 list
[1,2]

_.intersection([arrays])

使用 SameValueZero 判断相等,返回所有给定数组共有的唯一值组成的数组。结果的顺序和引用由第一个数组决定。

  • arrays ...Array 可选 要检查的数组列表。

→ Array

_.intersection([2, 1], [2, 3])
结果 list
[2]

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

与 _.intersection 类似,但接受一个 iteratee,对每个数组的每个元素调用它以生成比较依据。结果的顺序和引用由第一个数组决定。iteratee 调用时传入一个参数:(value)。

  • arrays ...Array 可选 要检查的数组列表。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Array

_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor)
结果 list
[2.1]
_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x')
结果 list
[{"x":1}]

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

与 _.intersection 类似,但接受一个 comparator 来比较各数组的元素。结果的顺序和引用由第一个数组决定。comparator 调用时传入两个参数:(arrVal, othVal)。

  • arrays ...Array 可选 要检查的数组列表。
  • comparator Function 可选 对每个元素调用的比较函数(comparator)。

→ Array

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.intersectionWith(objects, others, _.isEqual)
结果 list
[{"x":1,"y":2}]

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

将 array 的所有元素转换为以 separator 分隔的字符串。

  • array Array 要转换的数组。
  • separator string 可选 默认值 ',' 元素分隔符。

→ string

_.join(['a', 'b', 'c'], '~')
结果 string
"a~b~c"

_.last(array)

获取 array 的最后一个元素。

  • array Array 要查询的数组。

→ *

_.last([1, 2, 3])
结果 number
3

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

与 _.indexOf 类似,但从右向左遍历 array 的元素。

  • array Array 要检查的数组。
  • value * 要查找的值。
  • fromIndex number 可选 默认值 array.length-1 开始查找的索引。

→ number

_.lastIndexOf([1, 2, 1, 2], 2)
结果 number
3
_.lastIndexOf([1, 2, 1, 2], 2, 2)
结果 number
1

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

获取 array 中索引为 n 的元素;n 为负数时返回倒数第 n 个元素。

  • array Array 要查询的数组。
  • n number 可选 默认值 0 要返回的元素索引。

→ *

var array = ['a', 'b', 'c', 'd'];
_.nth(array, 1)
结果 string
"b"
var array = ['a', 'b', 'c', 'd'];
_.nth(array, -2)
结果 string
"c"

_.pull(array, [values])

使用 SameValueZero 判断相等,从 array 中移除所有给定的值。

注意: 与 _.without 不同,此方法会修改 array。如需按断言移除元素,请使用 _.remove。

  • array Array 要修改的数组。
  • values ...* 可选 要移除的值。

→ Array

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log(array)
结果 undefined
undefined

_.pullAll(array, values)

与 _.pull 类似,但接受一个由待移除值组成的数组。

注意: 与 _.difference 不同,此方法会修改 array。

  • array Array 要修改的数组。
  • values Array 要移除的值。

→ Array

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log(array)
结果 undefined
undefined

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

与 _.pullAll 类似,但接受一个 iteratee,对 array 和 values 的每个元素调用它以生成比较依据。iteratee 调用时传入一个参数:(value)。

注意: 与 _.differenceBy 不同,此方法会修改 array。

  • array Array 要修改的数组。
  • values Array 要移除的值。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Array

var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
console.log(array)
结果 undefined
undefined

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

与 _.pullAll 类似,但接受一个 comparator 来比较 array 与 values 的元素。comparator 调用时传入两个参数:(arrVal, othVal)。

注意: 与 _.differenceWith 不同,此方法会修改 array。

  • array Array 要修改的数组。
  • values Array 要移除的值。
  • comparator Function 可选 对每个元素调用的比较函数(comparator)。

→ Array

var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
console.log(array)
结果 undefined
undefined

_.pullAt(array, [indexes])

从 array 中移除 indexes 对应的元素,并返回被移除元素组成的数组。

注意: 与 _.at 不同,此方法会修改 array。

  • array Array 要修改的数组。
  • indexes ...(number|number[]) 可选 要移除元素的索引。

→ Array

var array = ['a', 'b', 'c', 'd'];
var pulled = _.pullAt(array, [1, 3]);
console.log(array)
结果 undefined
undefined
var array = ['a', 'b', 'c', 'd'];
var pulled = _.pullAt(array, [1, 3]);
console.log(pulled)
结果 undefined
undefined

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

从 array 中移除所有使 predicate 返回真值的元素,并返回被移除元素组成的数组。predicate 调用时传入三个参数:(value, index, array)。

注意: 与 _.filter 不同,此方法会修改 array。如需按值移除元素,请使用 _.pull。

  • array Array 要修改的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});
console.log(array)
结果 undefined
undefined
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});
console.log(evens)
结果 undefined
undefined

_.reverse(array)

反转 array,使第一个元素变为最后一个,第二个变为倒数第二个,依此类推。

注意: 此方法会修改 array,基于 Array#reverse。

  • array Array 要修改的数组。

→ Array

var array = [1, 2, 3];
_.reverse(array)
结果 list
[3,2,1]
var array = [1, 2, 3];
console.log(array)
结果 undefined
undefined

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

创建 array 从 start 到 end(不含)的切片。

注意: 使用此方法而非 Array#slice,可确保返回稠密数组。

  • array Array 要切片的数组。
  • start number 可选 默认值 0 起始位置。
  • end number 可选 默认值 array.length 结束位置。

→ Array

_.sortedIndex(array, value)

通过二分查找,确定 value 应插入 array 的最小索引,以保持数组有序。

  • array Array 要检查的已排序数组。
  • value * 要求值的值。

→ number

_.sortedIndex([30, 50], 40)
结果 number
1

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

与 _.sortedIndex 类似,但接受一个 iteratee,对 value 和 array 的每个元素调用它以计算排序依据。iteratee 调用时传入一个参数:(value)。

  • array Array 要检查的已排序数组。
  • value * 要求值的值。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ number

var objects = [{ 'x': 4 }, { 'x': 5 }];
_.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; })
结果 number
0
var objects = [{ 'x': 4 }, { 'x': 5 }];
_.sortedIndexBy(objects, { 'x': 4 }, 'x')
结果 number
0

_.sortedIndexOf(array, value)

与 _.indexOf 类似,但对已排序的 array 执行二分查找。

  • array Array 要检查的数组。
  • value * 要查找的值。

→ number

_.sortedIndexOf([4, 5, 5, 5, 6], 5)
结果 number
1

_.sortedLastIndex(array, value)

与 _.sortedIndex 类似,但返回 value 应插入 array 的最大索引,以保持数组有序。

  • array Array 要检查的已排序数组。
  • value * 要求值的值。

→ number

_.sortedLastIndex([4, 5, 5, 5, 6], 5)
结果 number
4

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

与 _.sortedLastIndex 类似,但接受一个 iteratee,对 value 和 array 的每个元素调用它以计算排序依据。iteratee 调用时传入一个参数:(value)。

  • array Array 要检查的已排序数组。
  • value * 要求值的值。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ number

var objects = [{ 'x': 4 }, { 'x': 5 }];
_.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; })
结果 number
1
var objects = [{ 'x': 4 }, { 'x': 5 }];
_.sortedLastIndexBy(objects, { 'x': 4 }, 'x')
结果 number
1

_.sortedLastIndexOf(array, value)

与 _.lastIndexOf 类似,但对已排序的 array 执行二分查找。

  • array Array 要检查的数组。
  • value * 要查找的值。

→ number

_.sortedLastIndexOf([4, 5, 5, 5, 6], 5)
结果 number
3

_.sortedUniq(array)

与 _.uniq 类似,但专为已排序数组设计并做了优化。

  • array Array 要检查的数组。

→ Array

_.sortedUniq([1, 1, 2])
结果 list
[1,2]

_.sortedUniqBy(array, [iteratee])

与 _.uniqBy 类似,但专为已排序数组设计并做了优化。

  • array Array 要检查的数组。
  • iteratee Function 可选 对每个元素调用的 iteratee。

→ Array

_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor)
结果 list
[1.1,2.3]

_.tail(array)

获取 array 除第一个元素外的所有元素。

  • array Array 要查询的数组。

→ Array

_.tail([1, 2, 3])
结果 list
[2,3]

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

创建 array 的切片,从开头取 n 个元素。

  • array Array 要查询的数组。
  • n number 可选 默认值 1 要获取的元素个数。

→ Array

_.take([1, 2, 3])
结果 list
[1]
_.take([1, 2, 3], 2)
结果 list
[1,2]
_.take([1, 2, 3], 5)
结果 list
[1,2,3]
_.take([1, 2, 3], 0)
结果 list
[]

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

创建 array 的切片,从末尾取 n 个元素。

  • array Array 要查询的数组。
  • n number 可选 默认值 1 要获取的元素个数。

→ Array

_.takeRight([1, 2, 3])
结果 list
[3]
_.takeRight([1, 2, 3], 2)
结果 list
[2,3]
_.takeRight([1, 2, 3], 5)
结果 list
[1,2,3]
_.takeRight([1, 2, 3], 0)
结果 list
[]

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

创建 array 的切片,从末尾开始取元素,直到 predicate 返回假值为止。predicate 调用时传入三个参数:(value, index, array)。

  • array Array 要查询的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.takeRightWhile(users, function(o) { return !o.active; })
结果 list
[{"user":"fred","active":false},{"user":"pebbles","active":false}]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.takeRightWhile(users, { 'user': 'pebbles', 'active': false })
结果 list
[{"user":"pebbles","active":false}]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.takeRightWhile(users, ['active', false])
结果 list
[{"user":"fred","active":false},{"user":"pebbles","active":false}]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];
_.takeRightWhile(users, 'active')
结果 list
[]

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

创建 array 的切片,从开头开始取元素,直到 predicate 返回假值为止。predicate 调用时传入三个参数:(value, index, array)。

  • array Array 要查询的数组。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; })
结果 list
[{"user":"barney","active":false},{"user":"fred","active":false}]
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, { 'user': 'barney', 'active': false })
结果 list
[{"user":"barney","active":false}]
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, ['active', false])
结果 list
[{"user":"barney","active":false},{"user":"fred","active":false}]
var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, 'active')
结果 list
[]

_.union([arrays])

使用 SameValueZero 判断相等,按顺序返回所有给定数组中唯一值组成的数组(并集)。

  • arrays ...Array 可选 要检查的数组列表。

→ Array

_.union([2], [1, 2])
结果 list
[2,1]

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

与 _.union 类似,但接受一个 iteratee,对每个数组的每个元素调用它以生成判断唯一性的依据。结果值取自该值最先出现的数组。iteratee 调用时传入一个参数:(value)。

  • arrays ...Array 可选 要检查的数组列表。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Array

_.unionBy([2.1], [1.2, 2.3], Math.floor)
结果 list
[2.1,1.2]
_.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x')
结果 list
[{"x":1},{"x":2}]

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

与 _.union 类似,但接受一个 comparator 来比较各数组的元素。结果值取自该值最先出现的数组。comparator 调用时传入两个参数:(arrVal, othVal)。

  • arrays ...Array 可选 要检查的数组列表。
  • comparator Function 可选 对每个元素调用的比较函数(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)
结果 list
[{"x":1,"y":2},{"x":2,"y":1},{"x":1,"y":1}]

_.uniq(array)

使用 SameValueZero 判断相等,返回去重后的数组,每个元素只保留首次出现的那个。结果顺序与元素在原数组中出现的顺序一致。

  • array Array 要检查的数组。

→ Array

_.uniq([2, 1, 2])
结果 list
[2,1]

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

与 _.uniq 类似,但接受一个 iteratee,对 array 中每个元素调用它以生成判断唯一性的依据。结果顺序与元素在原数组中出现的顺序一致。iteratee 调用时传入一个参数:(value)。

  • array Array 要检查的数组。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Array

_.uniqBy([2.1, 1.2, 2.3], Math.floor)
结果 list
[2.1,1.2]
_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x')
结果 list
[{"x":1},{"x":2}]

_.uniqWith(array, [comparator])

与 _.uniq 类似,但接受一个 comparator 来比较 array 的元素。结果顺序与元素在原数组中出现的顺序一致。comparator 调用时传入两个参数:(arrVal, othVal)。

  • array Array 要检查的数组。
  • comparator Function 可选 对每个元素调用的比较函数(comparator)。

→ Array

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual)
结果 list
[{"x":1,"y":2},{"x":2,"y":1}]

_.unzip(array)

与 _.zip 类似,但接受一个分组元素数组,并将元素重新分组为 zip 之前的结构。

  • array Array 要处理的分组元素数组。

→ Array

var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
_.unzip(zipped)
结果 list
[["a","b"],[1,2],[true,false]]

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

与 _.unzip 类似,但接受一个 iteratee 来指定如何合并重新分组后的值。iteratee 调用时传入每组的元素:(...group)。

  • array Array 要处理的分组元素数组。
  • iteratee Function 可选 默认值 _.identity 用于合并重新分组后各值的函数。

→ Array

var zipped = _.zip([1, 2], [10, 20], [100, 200]);
_.unzipWith(zipped, _.add)
结果 list
[3,30,300]

_.without(array, [values])

使用 SameValueZero 判断相等,返回排除了所有给定值的新数组。

注意: 与 _.pull 不同,此方法返回新数组。

  • array Array 要检查的数组。
  • values ...* 可选 要排除的值。

→ Array

_.without([2, 1, 2, 3], 1, 2)
结果 list
[3]

_.xor([arrays])

返回给定数组的 对称差 中唯一值组成的数组。结果顺序与值在各数组中出现的顺序一致。

  • arrays ...Array 可选 要检查的数组列表。

→ Array

_.xor([2, 1], [2, 3])
结果 list
[1,3]

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

与 _.xor 类似,但接受一个 iteratee,对每个数组的每个元素调用它以生成比较依据。结果顺序与值在各数组中出现的顺序一致。iteratee 调用时传入一个参数:(value)。

  • arrays ...Array 可选 要检查的数组列表。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Array

_.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor)
结果 list
[1.2,3.4]
_.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x')
结果 list
[{"x":2}]

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

与 _.xor 类似,但接受一个 comparator 来比较各数组的元素。结果顺序与值在各数组中出现的顺序一致。comparator 调用时传入两个参数:(arrVal, othVal)。

  • arrays ...Array 可选 要检查的数组列表。
  • comparator Function 可选 对每个元素调用的比较函数(comparator)。

→ Array

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.xorWith(objects, others, _.isEqual)
结果 list
[{"x":2,"y":1},{"x":1,"y":1}]

_.zip([arrays])

创建一个分组元素数组:第一组包含各给定数组的第一个元素,第二组包含各数组的第二个元素,依此类推。

  • arrays ...Array 可选 要处理的数组列表。

→ Array

_.zip(['a', 'b'], [1, 2], [true, false])
结果 list
[["a",1,true],["b",2,false]]

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

与 _.fromPairs 类似,但接受两个数组:一个是属性标识符,另一个是对应的值。

  • props Array 可选 默认值 [ 属性标识符(键名)。
  • values Array 可选 默认值 [ 属性值。

→ Object

_.zipObject(['a', 'b'], [1, 2])
结果 object
{"a":1,"b":2}

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

与 _.zipObject 类似,但支持属性路径。

  • props Array 可选 默认值 [ 属性标识符(键名)。
  • values Array 可选 默认值 [ 属性值。

→ Object

_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2])
结果 object
{"a":{"b":[{"c":1},{"d":2}]}}

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

与 _.zip 类似,但接受一个 iteratee 来指定如何合并分组后的值。iteratee 调用时传入每组的元素:(...group)。

  • arrays ...Array 可选 要处理的数组列表。
  • iteratee Function 可选 默认值 _.identity 用于合并分组后各值的函数。

→ Array

_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
  return a + b + c;
})
结果 list
[111,222]

Collection

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

创建一个对象,键为 collection 中每个元素经 iteratee 处理后的结果,值为该键被 iteratee 返回的次数。iteratee 调用时传入一个参数:(value)。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 用于生成键的 iteratee。

→ Object

_.countBy([6.1, 4.2, 6.3], Math.floor)
结果 object
{"4":1,"6":2}
_.countBy(['one', 'two', 'three'], 'length')
结果 object
{"3":2,"5":1}

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

检查 predicate 是否对 collection 的所有元素都返回真值;一旦返回假值即停止遍历。predicate 调用时传入三个参数:(value, index|key, collection)。

注意: 对于 空集合,此方法返回 true,因为空集合的元素 满足任何条件。

  • collection Array|Object 要遍历的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ boolean

_.every([true, 1, null, 'yes'], Boolean)
结果 boolean
false
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.every(users, { 'user': 'barney', 'active': false })
结果 boolean
false
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.every(users, ['active', false])
结果 boolean
true
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.every(users, 'active')
结果 boolean
false

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

遍历 collection,返回由 predicate 返回真值的所有元素组成的数组。predicate 调用时传入三个参数:(value, index|key, collection)。

注意: 与 _.remove 不同,此方法返回新数组。

  • collection Array|Object 要遍历的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; })
结果 list
[{"user":"fred","age":40,"active":false}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(users, { 'age': 36, 'active': true })
结果 list
[{"user":"barney","age":36,"active":true}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(users, ['active', false])
结果 list
[{"user":"fred","age":40,"active":false}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(users, 'active')
结果 list
[{"user":"barney","age":36,"active":true}]

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

遍历 collection,返回第一个使 predicate 返回真值的元素。predicate 调用时传入三个参数:(value, index|key, collection)。

  • collection Array|Object 要检查的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • fromIndex number 可选 默认值 0 开始查找的索引。

→ *

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
{"user":"barney","age":36,"active":true}
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];
_.find(users, { 'age': 1, 'active': true })
结果 object
{"user":"pebbles","age":1,"active":true}
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];
_.find(users, ['active', false])
结果 object
{"user":"fred","age":40,"active":false}
var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];
_.find(users, 'active')
结果 object
{"user":"barney","age":36,"active":true}

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

与 _.find 类似,但从右向左遍历 collection。

  • collection Array|Object 要检查的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • fromIndex number 可选 默认值 collection.length-1 开始查找的索引。

→ *

_.findLast([1, 2, 3, 4], function(n) {
  return n % 2 == 1;
})
结果 number
3

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

对 collection 中每个元素调用 iteratee,再把映射结果展平一层,得到一个扁平数组。iteratee 调用时传入三个参数:(value, index|key, collection)。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

function duplicate(n) {
  return [n, n];
};
_.flatMap([1, 2], duplicate)
结果 list
[1,1,2,2]

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

与 _.flatMap 类似,但会递归展平映射结果。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

function duplicate(n) {
  return [[[n, n]]];
};
_.flatMapDeep([1, 2], duplicate)
结果 list
[1,1,2,2]

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

与 _.flatMap 类似,但最多递归展平映射结果 depth 层。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • depth number 可选 默认值 1 最大递归深度。

→ Array

function duplicate(n) {
  return [[[n, n]]];
};
_.flatMapDepth([1, 2], duplicate, 2)
结果 list
[[1,1],[2,2]]

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

遍历 collection 的元素并对每个元素调用 iteratee。iteratee 调用时传入三个参数:(value, index|key, collection)。iteratee 显式返回 false 可提前结束遍历。

注意: 与其他“集合”方法一样,带有 length 属性的对象会按数组方式遍历。若要避免这种行为,请使用 _.forIn 或 _.forOwn 遍历对象。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array|Object

_.forEach([1, 2], function(value) {
  console.log(value);
})
结果 list
[1,2]
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key);
})
结果 object
{"a":1,"b":2}

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

与 _.forEach 类似,但从右向左遍历 collection 的元素。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array|Object

_.forEachRight([1, 2], function(value) {
  console.log(value);
})
结果 list
[1,2]

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

创建一个对象,键为 collection 中每个元素经 iteratee 处理后的结果,值为生成该键的元素组成的数组。分组内元素的顺序与其在 collection 中出现的顺序一致。iteratee 调用时传入一个参数:(value)。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 用于生成键的 iteratee。

→ Object

_.groupBy([6.1, 4.2, 6.3], Math.floor)
结果 object
{"4":[4.2],"6":[6.1,6.3]}
_.groupBy(['one', 'two', 'three'], 'length')
结果 object
{"3":["one","two"],"5":["three"]}

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

检查 value 是否在 collection 中。若 collection 是字符串,则检查是否包含子串 value;否则使用 SameValueZero 判断相等。fromIndex 为负数时表示从 collection 末尾倒数的偏移。

  • collection Array|Object|string 要检查的集合。
  • value * 要查找的值。
  • fromIndex number 可选 默认值 0 开始查找的索引。

→ boolean

_.includes([1, 2, 3], 1)
结果 boolean
true
_.includes([1, 2, 3], 1, 2)
结果 boolean
false
_.includes({ 'a': 1, 'b': 2 }, 1)
结果 boolean
true
_.includes('abcd', 'bc')
结果 boolean
true

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

对 collection 中每个元素调用其 path 处的方法,返回各次调用结果组成的数组。额外参数会传给每次调用的方法。若 path 是函数,则以每个元素作为 this 调用它。

  • collection Array|Object 要遍历的集合。
  • path Array|Function|string 要调用的方法路径,或每次迭代时调用的函数。
  • args ...* 可选 调用每个方法时传入的参数。

→ Array

_.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort')
结果 list
[[1,5,7],[1,2,3]]
_.invokeMap([123, 456], String.prototype.split, '')
结果 list
[["1","2","3"],["4","5","6"]]

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

创建一个对象,键为 collection 中每个元素经 iteratee 处理后的结果,值为最后一个生成该键的元素。iteratee 调用时传入一个参数:(value)。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 用于生成键的 iteratee。

→ Object

var array = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];
_.keyBy(array, function(o) {
  return String.fromCharCode(o.code);
})
结果 object
{"a":{"dir":"left","code":97},"d":{"dir":"right","code":100}}
var array = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];
_.keyBy(array, 'dir')
结果 object
{"left":{"dir":"left","code":97},"right":{"dir":"right","code":100}}

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

对 collection 中每个元素调用 iteratee,返回结果组成的新数组。iteratee 调用时传入三个参数:(value, index|key, collection)。

许多 lodash 方法经过保护,可直接作为 _.every、_.filter、_.map、_.mapValues、_.reject 和 _.some 等方法的 iteratee。

这些受保护的方法有: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。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

function square(n) {
  return n * n;
};
_.map([4, 8], square)
结果 list
[16,64]
function square(n) {
  return n * n;
};
_.map({ 'a': 4, 'b': 8 }, square)
结果 list
[16,64]
function square(n) {
  return n * n;
};
var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];
_.map(users, 'user')
结果 list
["barney","fred"]

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

与 _.sortBy 类似,但允许为各排序 iteratee 指定排序方向。未指定 orders 时全部升序;否则对相应值指定 "desc"(降序)或 "asc"(升序)。

  • collection Array|Object 要遍历的集合。
  • iteratees Array[]|Function[]|Object[]|string[] 可选 默认值 [_.identity 用于排序的 iteratee。
  • orders string[] 可选 `iteratees` 对应的排序方向。

→ Array

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 34 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 36 }
];
_.orderBy(users, ['user', 'age'], ['asc', 'desc'])
结果 list
[
  {
    "user": "barney",
    "age": 36
  },
  {
    "user": "barney",
    "age": 34
  },
  {
    "user": "fred",
    "age": 48
  },
  {
    "user": "fred",
    "age": 40
  }
]

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

把元素拆分为两组并返回数组:第一组为 predicate 返回真值的元素,第二组为返回假值的元素。predicate 调用时传入一个参数:(value)。

  • collection Array|Object 要遍历的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

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; })
结果 list
[
  [
    {
      "user": "fred",
      "age": 40,
      "active": true
    }
  ],
  [
    {
      "user": "barney",
      "age": 36,
      "active": false
    },
    {
      "user": "pebbles",
      "age": 1,
      "active": false
    }
  ]
]
var users = [
  { 'user': 'barney',  'age': 36, 'active': false },
  { 'user': 'fred',    'age': 40, 'active': true },
  { 'user': 'pebbles', 'age': 1,  'active': false }
];
_.partition(users, { 'age': 1, 'active': false })
结果 list
[
  [
    {
      "user": "pebbles",
      "age": 1,
      "active": false
    }
  ],
  [
    {
      "user": "barney",
      "age": 36,
      "active": false
    },
    {
      "user": "fred",
      "age": 40,
      "active": true
    }
  ]
]
var users = [
  { 'user': 'barney',  'age': 36, 'active': false },
  { 'user': 'fred',    'age': 40, 'active': true },
  { 'user': 'pebbles', 'age': 1,  'active': false }
];
_.partition(users, ['active', false])
结果 list
[
  [
    {
      "user": "barney",
      "age": 36,
      "active": false
    },
    {
      "user": "pebbles",
      "age": 1,
      "active": false
    }
  ],
  [
    {
      "user": "fred",
      "age": 40,
      "active": true
    }
  ]
]
var users = [
  { 'user': 'barney',  'age': 36, 'active': false },
  { 'user': 'fred',    'age': 40, 'active': true },
  { 'user': 'pebbles', 'age': 1,  'active': false }
];
_.partition(users, 'active')
结果 list
[
  [
    {
      "user": "fred",
      "age": 40,
      "active": true
    }
  ],
  [
    {
      "user": "barney",
      "age": 36,
      "active": false
    },
    {
      "user": "pebbles",
      "age": 1,
      "active": false
    }
  ]
]

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

把 collection 归约为一个值:对每个元素依次调用 iteratee,每次调用都接收上一次的返回值。若未提供 accumulator,则以 collection 的第一个元素作为初始值。iteratee 调用时传入四个参数:(accumulator, value, index|key, collection)。

许多 lodash 方法经过保护,可直接作为 _.reduce、_.reduceRight 和 _.transform 等方法的 iteratee。

这些受保护的方法有:assign、defaults、defaultsDeep、includes、merge、orderBy 和 sortBy。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • accumulator * 可选 初始值。

→ *

_.reduce([1, 2], function(sum, n) {
  return sum + n;
}, 0)
结果 number
3
_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
  return result;
}, {})
结果 object
{"1":["a","c"],"2":["b"]}

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

与 _.reduce 类似,但从右向左遍历 collection 的元素。

  • collection Array|Object 要遍历的集合。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • accumulator * 可选 初始值。

→ *

var array = [[0, 1], [2, 3], [4, 5]];
_.reduceRight(array, function(flattened, other) {
  return flattened.concat(other);
}, [])
结果 list
[4,5,2,3,0,1]

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

与 _.filter 相反:返回 collection 中 predicate 未返回真值的元素。

  • collection Array|Object 要遍历的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': true }
];
_.reject(users, function(o) { return !o.active; })
结果 list
[{"user":"fred","age":40,"active":true}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': true }
];
_.reject(users, { 'age': 40, 'active': true })
结果 list
[{"user":"barney","age":36,"active":false}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': true }
];
_.reject(users, ['active', false])
结果 list
[{"user":"fred","age":40,"active":true}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': true }
];
_.reject(users, 'active')
结果 list
[{"user":"barney","age":36,"active":false}]

_.sample(collection)

从 collection 中随机取一个元素。

  • collection Array|Object 要从中抽样的集合。

→ *

_.sample([1, 2, 3, 4])
结果 number
3

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

从 collection 中随机取 n 个键不重复的元素,最多取到 collection 的大小。

  • collection Array|Object 要从中抽样的集合。
  • n number 可选 默认值 1 要抽取的元素个数。

→ Array

_.sampleSize([1, 2, 3], 2)
结果 list
[3,2]
_.sampleSize([1, 2, 3], 4)
结果 list
[2,3,1]

_.shuffle(collection)

使用 Fisher-Yates 洗牌算法 的一种变体,返回打乱顺序后的值组成的数组。

  • collection Array|Object 要打乱顺序的集合。

→ Array

_.shuffle([1, 2, 3, 4])
结果 list
[2,1,3,4]

_.size(collection)

获取 collection 的大小:类数组值返回其长度,对象返回自身可枚举字符串键属性的个数。

  • collection Array|Object|string 要检查的集合。

→ number

_.size([1, 2, 3])
结果 number
3
_.size({ 'a': 1, 'b': 2 })
结果 number
2
_.size('pebbles')
结果 number
7

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

检查 predicate 是否对 collection 的任一元素返回真值;一旦返回真值即停止遍历。predicate 调用时传入三个参数:(value, index|key, collection)。

  • collection Array|Object 要遍历的集合。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ boolean

_.some([null, 0, 'yes', false], Boolean)
结果 boolean
true
var users = [
  { 'user': 'barney', 'active': true },
  { 'user': 'fred',   'active': false }
];
_.some(users, { 'user': 'barney', 'active': false })
结果 boolean
false
var users = [
  { 'user': 'barney', 'active': true },
  { 'user': 'fred',   'active': false }
];
_.some(users, ['active', false])
结果 boolean
true
var users = [
  { 'user': 'barney', 'active': true },
  { 'user': 'fred',   'active': false }
];
_.some(users, 'active')
结果 boolean
true

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

对集合中每个元素依次调用各个 iteratee,按结果升序排列并返回新数组。此方法为稳定排序,即相等元素保持原有顺序。iteratee 调用时传入一个参数:(value)。

  • collection Array|Object 要遍历的集合。
  • iteratees ...(Function|Function[]) 可选 默认值 [_.identity 用于排序的 iteratee。

→ Array

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 30 },
  { 'user': 'barney', 'age': 34 }
];
_.sortBy(users, [function(o) { return o.user; }])
结果 list
[
  {
    "user": "barney",
    "age": 36
  },
  {
    "user": "barney",
    "age": 34
  },
  {
    "user": "fred",
    "age": 48
  },
  {
    "user": "fred",
    "age": 30
  }
]
var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 30 },
  { 'user': 'barney', 'age': 34 }
];
_.sortBy(users, ['user', 'age'])
结果 list
[
  {
    "user": "barney",
    "age": 34
  },
  {
    "user": "barney",
    "age": 36
  },
  {
    "user": "fred",
    "age": 30
  },
  {
    "user": "fred",
    "age": 48
  }
]

Date

_.now()

获取自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来经过的毫秒数时间戳。

→ number

_.defer(function(stamp) {
  console.log(_.now() - stamp);
}, _.now())
结果 object
"[Timeout]"

Function

_.after(n, func)

与 _.before 相反:创建一个函数,被调用 n 次及以上后才会执行 func。

  • n number 执行 `func` 之前需要的调用次数。
  • func Function 要限制调用的函数。

→ Function

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

创建一个调用 func 的函数,最多只传入 n 个参数,多余参数会被忽略。

  • func Function 要限制参数个数的函数。
  • n number 可选 默认值 func.length 参数个数上限。

→ Function

_.map(['6', '8', '10'], _.ary(parseInt, 1))
结果 list
[6,8,10]

_.before(n, func)

创建一个函数,在其被调用次数少于 n 次时,以该函数的 this 绑定和参数调用 func;之后的调用直接返回最后一次 func 调用的结果。

  • n number 从第几次调用起不再执行 `func`。
  • func Function 要限制调用的函数。

→ Function

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

创建一个函数,以 thisArg 作为 this 调用 func,并把 partials 放在接收到的参数之前。

_.bind.placeholder(在完整构建中默认为 _)可作为部分应用参数的占位符。

注意: 与原生 Function#bind 不同,此方法不会设置绑定函数的 length 属性。

  • func Function 要绑定的函数。
  • thisArg * `func` 的 `this` 绑定。
  • partials ...* 可选 要预先绑定(部分应用)的参数。

→ Function

function greet(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
};
var object = { 'user': 'fred' };
var bound = _.bind(greet, object, 'hi');
bound('!')
结果 string
"hi fred!"
function greet(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
};
var object = { 'user': 'fred' };
var bound = _.bind(greet, object, 'hi');
var bound = _.bind(greet, object, _, '!');
bound('hi')
结果 string
"hi fred!"

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

创建一个函数,调用 object[key] 上的方法,并把 partials 放在接收到的参数之前。

与 _.bind 的区别在于,被绑定的方法可以是之后才重新定义或尚不存在的方法。详见 Peter Michaux 的文章。

_.bindKey.placeholder(在完整构建中默认为 _)可作为部分应用参数的占位符。

  • object Object 调用方法所在的对象。
  • key string 方法的键名。
  • partials ...* 可选 要预先绑定(部分应用)的参数。

→ Function

var object = {
  'user': 'fred',
  'greet': function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};
var bound = _.bindKey(object, 'greet', 'hi');
bound('!')
结果 string
"hi fred!"
var object = {
  'user': 'fred',
  'greet': function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};
var bound = _.bindKey(object, 'greet', 'hi');
bound('!')
结果 string
"hi fred!"
var object = {
  'user': 'fred',
  'greet': function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};
var bound = _.bindKey(object, 'greet', 'hi');
var bound = _.bindKey(object, 'greet', _, '!');
bound('hi')
结果 string
"hi fred!"

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

创建一个接收 func 参数的函数:若已提供的参数数量达到 arity,则调用 func 并返回结果;否则返回一个接收剩余参数的函数,依此类推。若 func.length 不够用,可显式指定 func 的参数个数。

_.curry.placeholder(在完整构建中默认为 _)可作为已提供参数的占位符。

注意: 此方法不会设置柯里化函数的 length 属性。

  • func Function 要柯里化的函数。
  • arity number 可选 默认值 func.length `func` 的参数个数(arity)。

→ Function

var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curry(abc);
curried(1)(2)(3)
结果 list
[1,2,3]
var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curry(abc);
curried(1, 2)(3)
结果 list
[1,2,3]
var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curry(abc);
curried(1, 2, 3)
结果 list
[1,2,3]
var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curry(abc);
curried(1)(_, 3)(2)
结果 list
[1,2,3]

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

与 _.curry 类似,但参数以 _.partialRight 而非 _.partial 的方式应用到 func(从右侧开始)。

_.curryRight.placeholder(在完整构建中默认为 _)可作为已提供参数的占位符。

注意: 此方法不会设置柯里化函数的 length 属性。

  • func Function 要柯里化的函数。
  • arity number 可选 默认值 func.length `func` 的参数个数(arity)。

→ Function

var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curryRight(abc);
curried(3)(2)(1)
结果 list
[1,2,3]
var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curryRight(abc);
curried(2, 3)(1)
结果 list
[1,2,3]
var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curryRight(abc);
curried(1, 2, 3)
结果 list
[1,2,3]
var abc = function(a, b, c) {
  return [a, b, c];
};
var curried = _.curryRight(abc);
curried(3)(1, _)(2)
结果 list
[1,2,3]

_.debounce(func, [wait=0], [options={}], [options.leading=false], [options.maxWait], [options.trailing=true])

创建一个防抖函数:自上次调用起经过 wait 毫秒后才调用 func。防抖函数提供 cancel 方法用于取消延迟调用,提供 flush 方法用于立即执行。通过 options 指定在等待开始(leading)和/或结束(trailing)时调用 func。func 以最后一次传给防抖函数的参数调用;后续调用返回最后一次 func 调用的结果。

注意: 若 leading 和 trailing 均为 true,只有在 wait 期间防抖函数被调用超过一次时,才会在结束时调用 func。

若 wait 为 0 且 leading 为 false,func 会被推迟到下一个 tick 执行,效果类似 setTimeout(fn, 0)。

_.debounce 与 _.throttle 的区别参见 David Corbacho 的文章。

  • func Function 要防抖的函数。
  • wait number 可选 默认值 0 延迟的毫秒数。
  • options Object 可选 默认值 {} 选项对象。
  • options.leading boolean 可选 默认值 false 是否在等待时间开始时(leading edge)调用。
  • options.maxWait number 可选 `func` 在被调用前允许延迟的最长时间。
  • options.trailing boolean 可选 默认值 true 是否在等待时间结束时(trailing edge)调用。

→ Function

_.defer(func, [args])

推迟调用 func,直到当前调用栈清空。额外传入的参数会在调用时转交给 func。

  • func Function 要推迟调用的函数。
  • args ...* 可选 调用 `func` 时传入的参数。

→ number

_.defer(function(text) {
  console.log(text);
}, 'deferred')
结果 object
"[Timeout]"

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

在 wait 毫秒后调用 func。额外传入的参数会在调用时转交给 func。

  • func Function 要延迟调用的函数。
  • wait number 延迟调用的毫秒数。
  • args ...* 可选 调用 `func` 时传入的参数。

→ number

_.delay(function(text) {
  console.log(text);
}, 1000, 'later')
结果 object
"[Timeout]"

_.flip(func)

创建一个函数,以反转后的参数顺序调用 func。

  • func Function 要反转参数顺序的函数。

→ Function

var flipped = _.flip(function() {
  return _.toArray(arguments);
});
flipped('a', 'b', 'c', 'd')
结果 list
["d","c","b","a"]

_.memoize(func, [resolver])

创建一个缓存 func 结果的函数。若提供 resolver,则由它根据传入的参数决定缓存键;默认使用第一个参数作为缓存键。func 以记忆化函数的 this 绑定调用。

注意: 缓存通过记忆化函数的 cache 属性暴露。可将 _.memoize.Cache 构造函数替换为实现了 clear、delete、get、has、set 这组 Map 方法接口的构造函数,以自定义缓存的创建。

  • func Function 要缓存其输出的函数。
  • resolver Function 可选 用于解析缓存键的函数。

→ Function

var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };
var values = _.memoize(_.values);
values(object)
结果 list
[1,2]
var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };
var values = _.memoize(_.values);
values(other)
结果 list
[3,4]
var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };
var values = _.memoize(_.values);
values(object)
结果 list
[1,2]
var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };
var values = _.memoize(_.values);
values(object)
结果 list
[1,2]

_.negate(predicate)

创建一个对断言函数 func 的结果取反的函数。func 以所创建函数的 this 绑定和参数调用。

  • predicate Function 要取反的断言函数。

→ Function

function isEven(n) {
  return n % 2 == 0;
};
_.filter([1, 2, 3, 4, 5, 6], _.negate(isEven))
结果 list
[1,3,5]

_.once(func)

创建一个只会调用 func 一次的函数,重复调用返回首次调用的结果。func 以所创建函数的 this 绑定和参数调用。

  • func Function 要限制调用的函数。

→ Function

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

创建一个函数,先转换参数,再用转换后的参数调用 func。

  • func Function 要包装的函数。
  • transforms ...(Function|Function[]) 可选 默认值 [_.identity 用于转换各参数的函数。

→ 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)
结果 list
[81,6]
function doubled(n) {
  return n * 2;
};
function square(n) {
  return n * n;
};
var func = _.overArgs(function(x, y) {
  return [x, y];
}, [square, doubled]);
func(10, 5)
结果 list
[100,10]

_.partial(func, [partials])

创建一个函数,调用 func 时把 partials 放在接收到的参数之前。与 _.bind 类似,但不会改变 this 绑定。

_.partial.placeholder(在完整构建中默认为 _)可作为部分应用参数的占位符。

注意: 此方法不会设置部分应用函数的 length 属性。

  • func Function 要部分应用参数的函数。
  • partials ...* 可选 要预先绑定(部分应用)的参数。

→ Function

function greet(greeting, name) {
  return greeting + ' ' + name;
};
var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred')
结果 string
"hello fred"
function greet(greeting, name) {
  return greeting + ' ' + name;
};
var sayHelloTo = _.partial(greet, 'hello');
var greetFred = _.partial(greet, _, 'fred');
greetFred('hi')
结果 string
"hi fred"

_.partialRight(func, [partials])

与 _.partial 类似,但部分应用的参数会追加在接收到的参数之后。

_.partialRight.placeholder(在完整构建中默认为 _)可作为部分应用参数的占位符。

注意: 此方法不会设置部分应用函数的 length 属性。

  • func Function 要部分应用参数的函数。
  • partials ...* 可选 要预先绑定(部分应用)的参数。

→ Function

function greet(greeting, name) {
  return greeting + ' ' + name;
};
var greetFred = _.partialRight(greet, 'fred');
greetFred('hi')
结果 string
"hi fred"
function greet(greeting, name) {
  return greeting + ' ' + name;
};
var greetFred = _.partialRight(greet, 'fred');
var sayHelloTo = _.partialRight(greet, 'hello', _);
sayHelloTo('fred')
结果 string
"hello fred"

_.rearg(func, indexes)

创建一个函数,按指定的 indexes 重新排列参数后调用 func:第一个索引处的参数作为第一个实参,第二个索引处的参数作为第二个实参,依此类推。

  • func Function 要重排参数的函数。
  • indexes ...(number|number[]) 重排后的参数索引。

→ Function

var rearged = _.rearg(function(a, b, c) {
  return [a, b, c];
}, [2, 0, 1]);
rearged('b', 'c', 'a')
结果 list
["a","b","c"]

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

创建一个函数,以该函数的 this 绑定调用 func,并把从 start 开始的参数收集为数组传入。

注意: 此方法基于 剩余参数(rest parameter)。

  • func Function 要应用剩余参数的函数。
  • start number 可选 默认值 func.length-1 剩余参数的起始位置。

→ Function

var say = _.rest(function(what, names) {
  return what + ' ' + _.initial(names).join(', ') +
    (_.size(names) > 1 ? ', & ' : '') + _.last(names);
});
say('hello', 'fred', 'barney', 'pebbles')
结果 string
"hello fred, barney, & pebbles"

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

创建一个函数,以该函数的 this 绑定和一个参数数组调用 func,效果类似 Function#apply。

注意: 此方法基于 展开运算符(spread operator)。

  • func Function 要展开参数调用的函数。
  • start number 可选 默认值 0 展开的起始位置。

→ Function

var say = _.spread(function(who, what) {
  return who + ' says ' + what;
});
say(['fred', 'hello'])
结果 string
"fred says hello"
var say = _.spread(function(who, what) {
  return who + ' says ' + what;
});
var numbers = Promise.all([
  Promise.resolve(40),
  Promise.resolve(36)
]);
numbers.then(_.spread(function(x, y) {
  return x + y;
}))
结果 object
{}

_.throttle(func, [wait=0], [options={}], [options.leading=true], [options.trailing=true])

创建一个节流函数:每 wait 毫秒最多调用一次 func。节流函数提供 cancel 方法用于取消延迟调用,提供 flush 方法用于立即执行。通过 options 指定在等待开始(leading)和/或结束(trailing)时调用 func。func 以最后一次传给节流函数的参数调用;后续调用返回最后一次 func 调用的结果。

注意: 若 leading 和 trailing 均为 true,只有在 wait 期间节流函数被调用超过一次时,才会在结束时调用 func。

若 wait 为 0 且 leading 为 false,func 会被推迟到下一个 tick 执行,效果类似 setTimeout(fn, 0)。

_.throttle 与 _.debounce 的区别参见 David Corbacho 的文章。

  • func Function 要节流的函数。
  • wait number 可选 默认值 0 节流的间隔毫秒数。
  • options Object 可选 默认值 {} 选项对象。
  • options.leading boolean 可选 默认值 true 是否在等待时间开始时(leading edge)调用。
  • options.trailing boolean 可选 默认值 true 是否在等待时间结束时(trailing edge)调用。

→ Function

_.unary(func)

创建一个最多只接受一个参数的函数,多余参数会被忽略。

  • func Function 要限制参数个数的函数。

→ Function

_.map(['6', '8', '10'], _.unary(parseInt))
结果 list
[6,8,10]

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

创建一个函数,把 value 作为第一个参数传给 wrapper;调用该函数时传入的其他参数追加在后面。wrapper 以所创建函数的 this 绑定调用。

  • value * 要包装的值。
  • wrapper Function 可选 默认值 identity 包装函数。

→ Function

var p = _.wrap(_.escape, function(func, text) {
  return '<p>' + func(text) + '</p>';
});
p('fred, barney, & pebbles')
结果 string
"<p>fred, barney, &amp; pebbles</p>"

Lang

_.castArray(value)

若 value 不是数组,则将其包装为数组。

  • value * 要处理的值。

→ Array

_.castArray(1)
结果 list
[1]
_.castArray({ 'a': 1 })
结果 list
[{"a":1}]
_.castArray('abc')
结果 list
["abc"]
_.castArray(null)
结果 list
[null]

_.clone(value)

创建 value 的浅拷贝。

注意: 此方法大致参照 结构化克隆算法,支持克隆数组、ArrayBuffer、布尔值、Date、Map、数字、Object 对象、正则、Set、字符串、Symbol 及类型化数组。arguments 对象自身的可枚举属性会被克隆为普通对象。对于错误对象、函数、DOM 节点和 WeakMap 等不可克隆的值,返回空对象。

  • value * 要克隆的值。

→ *

var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0])
结果 undefined
undefined

_.cloneDeep(value)

与 _.clone 类似,但会递归克隆 value(深拷贝)。

  • value * 要递归克隆的值。

→ *

var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0])
结果 undefined
undefined

_.cloneDeepWith(value, [customizer])

与 _.cloneWith 类似,但会递归克隆 value。

  • value * 要递归克隆的值。
  • customizer Function 可选 用于自定义克隆的函数。

→ *

_.cloneWith(value, [customizer])

与 _.clone 类似,但接受一个 customizer 来生成克隆值;若 customizer 返回 undefined,则交由方法本身处理克隆。customizer 最多传入四个参数:(value [, index|key, object, stack])。

  • value * 要克隆的值。
  • customizer Function 可选 用于自定义克隆的函数。

→ *

_.conformsTo(object, source)

用 source 中的断言属性检查 object 对应的属性值,判断 object 是否满足 source。

注意: 此方法等价于部分应用了 source 的 _.conforms。

  • object Object 要检查的对象。
  • source Object 由属性断言函数组成、需要满足的对象。

→ boolean

var object = { 'a': 1, 'b': 2 };
_.conformsTo(object, { 'b': function(n) { return n > 1; } })
结果 boolean
true
var object = { 'a': 1, 'b': 2 };
_.conformsTo(object, { 'b': function(n) { return n > 2; } })
结果 boolean
false

_.eq(value, other)

对两个值执行 SameValueZero 比较,判断它们是否相等。

  • value * 要比较的值。
  • other * 参与比较的另一个值。

→ boolean

var object = { 'a': 1 };
var other = { 'a': 1 };
_.eq(object, object)
结果 boolean
true
var object = { 'a': 1 };
var other = { 'a': 1 };
_.eq(object, other)
结果 boolean
false
var object = { 'a': 1 };
var other = { 'a': 1 };
_.eq('a', 'a')
结果 boolean
true
var object = { 'a': 1 };
var other = { 'a': 1 };
_.eq('a', Object('a'))
结果 boolean
false

_.gt(value, other)

检查 value 是否大于 other。

  • value * 要比较的值。
  • other * 参与比较的另一个值。

→ boolean

_.gt(3, 1)
结果 boolean
true
_.gt(3, 3)
结果 boolean
false
_.gt(1, 3)
结果 boolean
false

_.gte(value, other)

检查 value 是否大于或等于 other。

  • value * 要比较的值。
  • other * 参与比较的另一个值。

→ boolean

_.gte(3, 1)
结果 boolean
true
_.gte(3, 3)
结果 boolean
true
_.gte(1, 3)
结果 boolean
false

_.isArguments(value)

检查 value 是否可能是 arguments 对象。

  • value * 要检查的值。

→ boolean

_.isArguments(function() { return arguments; }())
结果 boolean
true
_.isArguments([1, 2, 3])
结果 boolean
false

_.isArray(value)

检查 value 是否为 Array 对象。

  • value * 要检查的值。

→ boolean

_.isArray([1, 2, 3])
结果 boolean
true
_.isArray('abc')
结果 boolean
false
_.isArray(_.noop)
结果 boolean
false

_.isArrayBuffer(value)

检查 value 是否为 ArrayBuffer 对象。

  • value * 要检查的值。

→ boolean

_.isArrayBuffer(new ArrayBuffer(2))
结果 boolean
true
_.isArrayBuffer(new Array(2))
结果 boolean
false

_.isArrayLike(value)

检查 value 是否为类数组。若值不是函数,且 value.length 是大于等于 0、小于等于 Number.MAX_SAFE_INTEGER 的整数,则视为类数组。

  • value * 要检查的值。

→ boolean

_.isArrayLike([1, 2, 3])
结果 boolean
true
_.isArrayLike('abc')
结果 boolean
true
_.isArrayLike(_.noop)
结果 boolean
false

_.isArrayLikeObject(value)

与 _.isArrayLike 类似,但还会检查 value 是否为对象。

  • value * 要检查的值。

→ boolean

_.isArrayLikeObject([1, 2, 3])
结果 boolean
true
_.isArrayLikeObject('abc')
结果 boolean
false
_.isArrayLikeObject(_.noop)
结果 boolean
false

_.isBoolean(value)

检查 value 是否为布尔原始值或布尔对象。

  • value * 要检查的值。

→ boolean

_.isBoolean(false)
结果 boolean
true
_.isBoolean(null)
结果 boolean
false

_.isBuffer(value)

检查 value 是否为 Buffer。

  • value * 要检查的值。

→ boolean

_.isBuffer(new Uint8Array(2))
结果 boolean
false

_.isDate(value)

检查 value 是否为 Date 对象。

  • value * 要检查的值。

→ boolean

_.isDate(new Date)
结果 boolean
true
_.isDate('Mon April 23 2012')
结果 boolean
false

_.isElement(value)

检查 value 是否可能是 DOM 元素。

  • value * 要检查的值。

→ boolean

_.isElement('<body>')
结果 boolean
false

_.isEmpty(value)

检查 value 是否为空对象、空集合、空 Map 或空 Set。

没有自身可枚举字符串键属性的对象视为空。

类数组值(如 arguments 对象、数组、Buffer、字符串或类 jQuery 集合)在 length 为 0 时视为空;同理,Map 和 Set 在 size 为 0 时视为空。

  • value * 要检查的值。

→ boolean

_.isEmpty(null)
结果 boolean
true
_.isEmpty(true)
结果 boolean
true
_.isEmpty(1)
结果 boolean
true
_.isEmpty([1, 2, 3])
结果 boolean
false

_.isEqual(value, other)

对两个值做深度比较,判断它们是否等价。

注意: 支持比较数组、ArrayBuffer、布尔值、Date、错误对象、Map、数字、Object 对象、正则、Set、字符串、Symbol 及类型化数组。Object 对象只比较自身(不含继承)的可枚举属性。函数和 DOM 节点按严格相等(===)比较。

  • value * 要比较的值。
  • other * 参与比较的另一个值。

→ boolean

var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other)
结果 boolean
true
var object = { 'a': 1 };
var other = { 'a': 1 };
object === other
结果 boolean
false

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

与 _.isEqual 类似,但接受一个 customizer 来比较值;若 customizer 返回 undefined,则交由方法本身比较。customizer 最多传入六个参数:(objValue, othValue [, index|key, object, other, stack])。

  • value * 要比较的值。
  • other * 参与比较的另一个值。
  • customizer Function 可选 用于自定义比较的函数。

→ boolean

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)
结果 boolean
true

_.isError(value)

检查 value 是否为 Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError 或 URIError 对象。

  • value * 要检查的值。

→ boolean

_.isError(new Error)
结果 boolean
true
_.isError(Error)
结果 boolean
false

_.isFinite(value)

检查 value 是否为有限的原始数字。

注意: 此方法基于 Number.isFinite。

  • value * 要检查的值。

→ boolean

_.isFinite(3)
结果 boolean
true
_.isFinite(Number.MIN_VALUE)
结果 boolean
true
_.isFinite(Infinity)
结果 boolean
false
_.isFinite('3')
结果 boolean
false

_.isFunction(value)

检查 value 是否为 Function 对象。

  • value * 要检查的值。

→ boolean

_.isFunction(_)
结果 boolean
true
_.isFunction(/abc/)
结果 boolean
false

_.isInteger(value)

检查 value 是否为整数。

注意: 此方法基于 Number.isInteger。

  • value * 要检查的值。

→ boolean

_.isInteger(3)
结果 boolean
true
_.isInteger(Number.MIN_VALUE)
结果 boolean
false
_.isInteger(Infinity)
结果 boolean
false
_.isInteger('3')
结果 boolean
false

_.isLength(value)

检查 value 是否为有效的类数组长度。

注意: 此方法大致参照 ToLength。

  • value * 要检查的值。

→ boolean

_.isLength(3)
结果 boolean
true
_.isLength(Number.MIN_VALUE)
结果 boolean
false
_.isLength(Infinity)
结果 boolean
false
_.isLength('3')
结果 boolean
false

_.isMap(value)

检查 value 是否为 Map 对象。

  • value * 要检查的值。

→ boolean

_.isMap(new Map)
结果 boolean
true
_.isMap(new WeakMap)
结果 boolean
false

_.isMatch(object, source)

对 object 与 source 做部分深度比较,判断 object 是否包含等价的属性值。

注意: 此方法等价于部分应用了 source 的 _.matches。

部分比较时,source 中的空数组和空对象分别与任意数组和对象值匹配。支持的比较类型见 _.isEqual。

  • object Object 要检查的对象。
  • source Object 用于匹配的属性值对象。

→ boolean

var object = { 'a': 1, 'b': 2 };
_.isMatch(object, { 'b': 2 })
结果 boolean
true
var object = { 'a': 1, 'b': 2 };
_.isMatch(object, { 'b': 1 })
结果 boolean
false

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

与 _.isMatch 类似,但接受一个 customizer 来比较值;若 customizer 返回 undefined,则交由方法本身比较。customizer 调用时传入五个参数:(objValue, srcValue, index|key, object, source)。

  • object Object 要检查的对象。
  • source Object 用于匹配的属性值对象。
  • customizer Function 可选 用于自定义比较的函数。

→ boolean

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)
结果 boolean
true

_.isNaN(value)

检查 value 是否为 NaN。

注意: 此方法基于 Number.isNaN,与全局 isNaN 不同:后者对 undefined 及其他非数字值也返回 true。

  • value * 要检查的值。

→ boolean

_.isNaN(NaN)
结果 boolean
true
_.isNaN(new Number(NaN))
结果 boolean
true
isNaN(undefined)
结果 boolean
true
_.isNaN(undefined)
结果 boolean
false

_.isNative(value)

检查 value 是否为未被改写的原生函数。

注意: 在存在 core-js 包时,此方法无法可靠地检测原生函数,因为 core-js 会规避此类检测;core-js 维护者明确表示不会配合修复,因此这种情况下只能抛出错误。依赖 core-js 的包(如 babel-polyfill)同样受影响。

  • value * 要检查的值。

→ boolean

_.isNative(Array.prototype.push)
结果 boolean
true
_.isNative(_)
结果 boolean
false

_.isNil(value)

检查 value 是否为 null 或 undefined。

  • value * 要检查的值。

→ boolean

_.isNil(null)
结果 boolean
true
_.isNil(void 0)
结果 boolean
true
_.isNil(NaN)
结果 boolean
false

_.isNull(value)

检查 value 是否为 null。

  • value * 要检查的值。

→ boolean

_.isNull(null)
结果 boolean
true
_.isNull(void 0)
结果 boolean
false

_.isNumber(value)

检查 value 是否为 Number 原始值或对象。

注意: Infinity、-Infinity 和 NaN 也属于数字;若要排除它们,请使用 _.isFinite。

  • value * 要检查的值。

→ boolean

_.isNumber(3)
结果 boolean
true
_.isNumber(Number.MIN_VALUE)
结果 boolean
true
_.isNumber(Infinity)
结果 boolean
true
_.isNumber('3')
结果 boolean
false

_.isObject(value)

检查 value 是否属于 Object 语言类型(例如数组、函数、对象、正则、new Number(0) 和 new String(''))。

  • value * 要检查的值。

→ boolean

_.isObject({})
结果 boolean
true
_.isObject([1, 2, 3])
结果 boolean
true
_.isObject(_.noop)
结果 boolean
true
_.isObject(null)
结果 boolean
false

_.isObjectLike(value)

检查 value 是否为类对象:值不为 null 且 typeof 结果为 "object"。

  • value * 要检查的值。

→ boolean

_.isObjectLike({})
结果 boolean
true
_.isObjectLike([1, 2, 3])
结果 boolean
true
_.isObjectLike(_.noop)
结果 boolean
false
_.isObjectLike(null)
结果 boolean
false

_.isPlainObject(value)

检查 value 是否为普通对象,即由 Object 构造函数创建、或 [[Prototype]] 为 null 的对象。

  • value * 要检查的值。

→ boolean

function Foo() {
  this.a = 1;
};
_.isPlainObject(new Foo)
结果 boolean
false
function Foo() {
  this.a = 1;
};
_.isPlainObject([1, 2, 3])
结果 boolean
false
function Foo() {
  this.a = 1;
};
_.isPlainObject({ 'x': 0, 'y': 0 })
结果 boolean
true
function Foo() {
  this.a = 1;
};
_.isPlainObject(Object.create(null))
结果 boolean
true

_.isRegExp(value)

检查 value 是否为 RegExp 对象。

  • value * 要检查的值。

→ boolean

_.isRegExp(/abc/)
结果 boolean
true
_.isRegExp('/abc/')
结果 boolean
false

_.isSafeInteger(value)

检查 value 是否为安全整数:即一个 IEEE-754 双精度数,且不是由不安全整数舍入得到的结果。

注意: 此方法基于 Number.isSafeInteger。

  • value * 要检查的值。

→ boolean

_.isSafeInteger(3)
结果 boolean
true
_.isSafeInteger(Number.MIN_VALUE)
结果 boolean
false
_.isSafeInteger(Infinity)
结果 boolean
false
_.isSafeInteger('3')
结果 boolean
false

_.isSet(value)

检查 value 是否为 Set 对象。

  • value * 要检查的值。

→ boolean

_.isSet(new Set)
结果 boolean
true
_.isSet(new WeakSet)
结果 boolean
false

_.isString(value)

检查 value 是否为 String 原始值或对象。

  • value * 要检查的值。

→ boolean

_.isString('abc')
结果 boolean
true
_.isString(1)
结果 boolean
false

_.isSymbol(value)

检查 value 是否为 Symbol 原始值或对象。

  • value * 要检查的值。

→ boolean

_.isSymbol(Symbol.iterator)
结果 boolean
true
_.isSymbol('abc')
结果 boolean
false

_.isTypedArray(value)

检查 value 是否为类型化数组(typed array)。

  • value * 要检查的值。

→ boolean

_.isTypedArray(new Uint8Array)
结果 boolean
true
_.isTypedArray([])
结果 boolean
false

_.isUndefined(value)

检查 value 是否为 undefined。

  • value * 要检查的值。

→ boolean

_.isUndefined(void 0)
结果 boolean
true
_.isUndefined(null)
结果 boolean
false

_.isWeakMap(value)

检查 value 是否为 WeakMap 对象。

  • value * 要检查的值。

→ boolean

_.isWeakMap(new WeakMap)
结果 boolean
true
_.isWeakMap(new Map)
结果 boolean
false

_.isWeakSet(value)

检查 value 是否为 WeakSet 对象。

  • value * 要检查的值。

→ boolean

_.isWeakSet(new WeakSet)
结果 boolean
true
_.isWeakSet(new Set)
结果 boolean
false

_.lt(value, other)

检查 value 是否小于 other。

  • value * 要比较的值。
  • other * 参与比较的另一个值。

→ boolean

_.lt(1, 3)
结果 boolean
true
_.lt(3, 3)
结果 boolean
false
_.lt(3, 1)
结果 boolean
false

_.lte(value, other)

检查 value 是否小于或等于 other。

  • value * 要比较的值。
  • other * 参与比较的另一个值。

→ boolean

_.lte(1, 3)
结果 boolean
true
_.lte(3, 3)
结果 boolean
true
_.lte(3, 1)
结果 boolean
false

_.toArray(value)

将 value 转换为数组。

  • value * 要转换的值。

→ Array

_.toArray({ 'a': 1, 'b': 2 })
结果 list
[1,2]
_.toArray('abc')
结果 list
["a","b","c"]
_.toArray(1)
结果 list
[]
_.toArray(null)
结果 list
[]

_.toFinite(value)

将 value 转换为有限数。

  • value * 要转换的值。

→ number

_.toFinite(3.2)
结果 number
3.2
_.toFinite(Number.MIN_VALUE)
结果 number
5e-324
_.toFinite(Infinity)
结果 number
1.7976931348623157e+308
_.toFinite('3.2')
结果 number
3.2

_.toInteger(value)

将 value 转换为整数。

注意: 此方法大致参照 ToInteger。

  • value * 要转换的值。

→ number

_.toInteger(3.2)
结果 number
3
_.toInteger(Number.MIN_VALUE)
结果 number
0
_.toInteger(Infinity)
结果 number
1.7976931348623157e+308
_.toInteger('3.2')
结果 number
3

_.toLength(value)

将 value 转换为可用作类数组对象长度的整数。

注意: 此方法基于 ToLength。

  • value * 要转换的值。

→ number

_.toLength(3.2)
结果 number
3
_.toLength(Number.MIN_VALUE)
结果 number
0
_.toLength(Infinity)
结果 number
4294967295
_.toLength('3.2')
结果 number
3

_.toNumber(value)

将 value 转换为数字。

  • value * 要处理的值。

→ number

_.toNumber(3.2)
结果 number
3.2
_.toNumber(Number.MIN_VALUE)
结果 number
5e-324
_.toNumber(Infinity)
结果 number
null
_.toNumber('3.2')
结果 number
3.2

_.toPlainObject(value)

将 value 转换为普通对象,并把其继承的可枚举字符串键属性展平为普通对象的自身属性。

  • value * 要转换的值。

→ Object

function Foo() {
  this.b = 2;
};
_.assign({ 'a': 1 }, new Foo)
结果 object
{"a":1,"b":2}
function Foo() {
  this.b = 2;
};
_.assign({ 'a': 1 }, _.toPlainObject(new Foo))
结果 object
{"a":1,"b":2}

_.toSafeInteger(value)

将 value 转换为安全整数,即能被正确比较和表示的整数。

  • value * 要转换的值。

→ number

_.toSafeInteger(3.2)
结果 number
3
_.toSafeInteger(Number.MIN_VALUE)
结果 number
0
_.toSafeInteger(Infinity)
结果 number
9007199254740991
_.toSafeInteger('3.2')
结果 number
3

_.toString(value)

将 value 转换为字符串。null 和 undefined 返回空字符串;-0 的符号会被保留。

  • value * 要转换的值。

→ string

_.toString(null)
结果 string
""
_.toString(-0)
结果 string
"-0"
_.toString([1, 2, 3])
结果 string
"1,2,3"

Math

_.add(augend, addend)

将两个数相加。

  • augend number 加法中的第一个数。
  • addend number 加法中的第二个数。

→ number

_.add(6, 4)
结果 number
10

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

将 number 按 precision 精度向上取整。

  • number number 要向上取整的数。
  • precision number 可选 默认值 0 向上取整的精度(小数位数)。

→ number

_.ceil(4.006)
结果 number
5
_.ceil(6.004, 2)
结果 number
6.01
_.ceil(6040, -2)
结果 number
6100

_.divide(dividend, divisor)

将两个数相除。

  • dividend number 除法中的第一个数(被除数)。
  • divisor number 除法中的第二个数(除数)。

→ number

_.divide(6, 4)
结果 number
1.5

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

将 number 按 precision 精度向下取整。

  • number number 要向下取整的数。
  • precision number 可选 默认值 0 向下取整的精度(小数位数)。

→ number

_.floor(4.006)
结果 number
4
_.floor(0.046, 2)
结果 number
0.04
_.floor(4060, -2)
结果 number
4000

_.max(array)

计算 array 中的最大值;若 array 为空或为假值,返回 undefined。

  • array Array 要遍历的数组。

→ *

_.max([4, 2, 8, 6])
结果 number
8
_.max([])
结果 undefined
undefined

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

与 _.max 类似,但接受一个 iteratee,对 array 中每个元素调用它以生成排序依据。iteratee 调用时传入一个参数:(value)。

  • array Array 要遍历的数组。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ *

var objects = [{ 'n': 1 }, { 'n': 2 }];
_.maxBy(objects, function(o) { return o.n; })
结果 object
{"n":2}
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.maxBy(objects, 'n')
结果 object
{"n":2}

_.mean(array)

计算 array 中各值的平均数。

  • array Array 要遍历的数组。

→ number

_.mean([4, 2, 8, 6])
结果 number
5

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

与 _.mean 类似,但接受一个 iteratee,对 array 中每个元素调用它以生成参与平均的值。iteratee 调用时传入一个参数:(value)。

  • array Array 要遍历的数组。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ number

var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.meanBy(objects, function(o) { return o.n; })
结果 number
5
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.meanBy(objects, 'n')
结果 number
5

_.min(array)

计算 array 中的最小值;若 array 为空或为假值,返回 undefined。

  • array Array 要遍历的数组。

→ *

_.min([4, 2, 8, 6])
结果 number
2
_.min([])
结果 undefined
undefined

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

与 _.min 类似,但接受一个 iteratee,对 array 中每个元素调用它以生成排序依据。iteratee 调用时传入一个参数:(value)。

  • array Array 要遍历的数组。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ *

var objects = [{ 'n': 1 }, { 'n': 2 }];
_.minBy(objects, function(o) { return o.n; })
结果 object
{"n":1}
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.minBy(objects, 'n')
结果 object
{"n":1}

_.multiply(multiplier, multiplicand)

将两个数相乘。

  • multiplier number 乘法中的第一个数。
  • multiplicand number 乘法中的第二个数。

→ number

_.multiply(6, 4)
结果 number
24

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

将 number 按 precision 精度四舍五入。

  • number number 要四舍五入的数。
  • precision number 可选 默认值 0 四舍五入的精度(小数位数)。

→ number

_.round(4.006)
结果 number
4
_.round(4.006, 2)
结果 number
4.01
_.round(4060, -2)
结果 number
4100

_.subtract(minuend, subtrahend)

将两个数相减。

  • minuend number 减法中的第一个数(被减数)。
  • subtrahend number 减法中的第二个数(减数)。

→ number

_.subtract(6, 4)
结果 number
2

_.sum(array)

计算 array 中各值的总和。

  • array Array 要遍历的数组。

→ number

_.sum([4, 2, 8, 6])
结果 number
20

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

与 _.sum 类似,但接受一个 iteratee,对 array 中每个元素调用它以生成参与求和的值。iteratee 调用时传入一个参数:(value)。

  • array Array 要遍历的数组。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ number

var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(objects, function(o) { return o.n; })
结果 number
20
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(objects, 'n')
结果 number
20

Number

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

把 number 限制在闭区间 [lower, upper] 内。

  • number number 要限制范围的数。
  • lower number 可选 下界。
  • upper number 上界。

→ number

_.clamp(-10, -5, 5)
结果 number
-5
_.clamp(10, -5, 5)
结果 number
5

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

检查 n 是否位于 start 到 end(不含)之间。若未指定 end,则把 start 作为 end,并将 start 设为 0。若 start 大于 end,两者会互换,以支持负数区间。

  • number number 要检查的数。
  • start number 可选 默认值 0 范围的起始值。
  • end number 范围的结束值。

→ boolean

_.inRange(3, 2, 4)
结果 boolean
true
_.inRange(4, 8)
结果 boolean
true
_.inRange(4, 2)
结果 boolean
false
_.inRange(2, 2)
结果 boolean
false

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

生成一个介于 lower 与 upper(均包含)之间的随机数。若只传入一个参数,则返回 0 到该数之间的数。若 floating 为 true,或 lower、upper 中有浮点数,则返回浮点数而非整数。

注意: JavaScript 采用 IEEE-754 标准处理浮点数,可能产生意料之外的结果。

注意: 若 lower 大于 upper,两者会互换。

  • lower number 可选 默认值 0 下界。
  • upper number 可选 默认值 1 上界。
  • floating boolean 可选 是否返回浮点数。

→ number

_.random(0, 5)
结果 number
1
_.random(5, 0)
结果 number
1
_.random(5)
结果 number
1
_.random(-5)
结果 number
-3

Object

_.assign(object, [sources])

把源对象自身的可枚举字符串键属性复制到目标对象。源对象从左到右依次应用,后面的源会覆盖前面源的同名属性。

注意: 此方法会修改 object,行为大致参照 Object.assign。

  • object Object 目标对象。
  • sources ...Object 可选 源对象。

→ Object

function Foo() {
  this.a = 1;
};
function Bar() {
  this.c = 3;
};
_.assign({ 'a': 0 }, new Foo, new Bar)
结果 object
{"a":1,"c":3}

_.assignIn(object, [sources])

与 _.assign 类似,但会遍历源对象自身及继承的属性。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 可选 源对象。

→ Object

function Foo() {
  this.a = 1;
};
function Bar() {
  this.c = 3;
};
_.assignIn({ 'a': 0 }, new Foo, new Bar)
结果 object
{"a":1,"c":3}

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

与 _.assignIn 类似,但接受一个 customizer 来生成要赋的值;若 customizer 返回 undefined,则交由方法本身处理赋值。customizer 调用时传入五个参数:(objValue, srcValue, key, object, source)。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 源对象。
  • customizer Function 可选 用于自定义赋值结果的函数。

→ Object

function customizer(objValue, srcValue) {
  return _.isUndefined(objValue) ? srcValue : objValue;
};
var defaults = _.partialRight(_.assignInWith, customizer);
defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 })
结果 object
{"a":1,"b":2}

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

与 _.assign 类似,但接受一个 customizer 来生成要赋的值;若 customizer 返回 undefined,则交由方法本身处理赋值。customizer 调用时传入五个参数:(objValue, srcValue, key, object, source)。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 源对象。
  • customizer Function 可选 用于自定义赋值结果的函数。

→ Object

function customizer(objValue, srcValue) {
  return _.isUndefined(objValue) ? srcValue : objValue;
};
var defaults = _.partialRight(_.assignWith, customizer);
defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 })
结果 object
{"a":1,"b":2}

_.at(object, [paths])

按 paths 从 object 中取值,返回由这些值组成的数组。

  • object Object 要遍历的对象。
  • paths ...(string|string[]) 可选 要选取的属性路径。

→ Array

var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
_.at(object, ['a[0].b.c', 'a[1]'])
结果 list
[3,4]

_.create(prototype, [properties])

创建一个继承自 prototype 对象的新对象。若提供了 properties 对象,其自身的可枚举字符串键属性会被赋给新对象。

  • prototype Object 要继承的原型对象。
  • properties Object 可选 要赋给新对象的属性。

→ Object

function Shape() {
  this.x = 0;
  this.y = 0;
};
function Circle() {
  Shape.call(this);
};
var circle = new Circle;
circle instanceof Circle
结果 boolean
true
function Shape() {
  this.x = 0;
  this.y = 0;
};
function Circle() {
  Shape.call(this);
};
var circle = new Circle;
circle instanceof Shape
结果 boolean
false

_.defaults(object, [sources])

对于目标对象中解析为 undefined 的属性,用源对象自身及继承的可枚举字符串键属性进行填充。源对象从左到右应用;某属性一旦被设置,后续同名属性值会被忽略。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 可选 源对象。

→ Object

_.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 })
结果 object
{"a":1,"b":2}

_.defaultsDeep(object, [sources])

与 _.defaults 类似,但会递归地填充默认属性。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 可选 源对象。

→ Object

_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } })
结果 object
{"a":{"b":2,"c":3}}

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

与 _.find 类似,但返回第一个使 predicate 返回真值的元素的键,而不是元素本身。

  • object Object 要检查的对象。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ string|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; })
结果 string
"barney"
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
_.findKey(users, { 'age': 1, 'active': true })
结果 string
"pebbles"
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
_.findKey(users, ['active', false])
结果 string
"fred"
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
_.findKey(users, 'active')
结果 string
"barney"

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

与 _.findKey 类似,但以相反顺序遍历集合元素。

  • object Object 要检查的对象。
  • predicate Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ string|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; })
结果 string
"pebbles"
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
_.findLastKey(users, { 'age': 36, 'active': true })
结果 string
"barney"
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
_.findLastKey(users, ['active', false])
结果 string
"fred"
var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
_.findLastKey(users, 'active')
结果 string
"pebbles"

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

遍历对象自身及继承的可枚举字符串键属性,并对每个属性调用 iteratee。iteratee 调用时传入三个参数:(value, key, object)。iteratee 显式返回 false 可提前结束遍历。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Object

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.forIn(new Foo, function(value, key) {
  console.log(key);
})
结果 object
{"a":1,"b":2}

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

与 _.forIn 类似,但以相反顺序遍历 object 的属性。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Object

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.forInRight(new Foo, function(value, key) {
  console.log(key);
})
结果 object
{"a":1,"b":2}

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

遍历对象自身的可枚举字符串键属性,并对每个属性调用 iteratee。iteratee 调用时传入三个参数:(value, key, object)。iteratee 显式返回 false 可提前结束遍历。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Object

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.forOwn(new Foo, function(value, key) {
  console.log(key);
})
结果 object
{"a":1,"b":2}

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

与 _.forOwn 类似,但以相反顺序遍历 object 的属性。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Object

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.forOwnRight(new Foo, function(value, key) {
  console.log(key);
})
结果 object
{"a":1,"b":2}

_.functions(object)

从 object 自身的可枚举属性中取出值为函数的属性名,返回由这些名称组成的数组。

  • object Object 要检查的对象。

→ Array

function Foo() {
  this.a = _.constant('a');
  this.b = _.constant('b');
};
_.functions(new Foo)
结果 list
["a","b"]

_.functionsIn(object)

从 object 自身及继承的可枚举属性中取出值为函数的属性名,返回由这些名称组成的数组。

  • object Object 要检查的对象。

→ Array

function Foo() {
  this.a = _.constant('a');
  this.b = _.constant('b');
};
_.functionsIn(new Foo)
结果 list
["a","b"]

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

获取 object 在 path 处的值;若解析结果为 undefined,则返回 defaultValue。

  • object Object 要查询的对象。
  • path Array|string 要获取的属性路径。
  • defaultValue * 可选 解析结果为 `undefined` 时返回的值。

→ *

var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c')
结果 number
3
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, ['a', '0', 'b', 'c'])
结果 number
3
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a.b.c', 'default')
结果 string
"default"

_.has(object, path)

检查 path 是否为 object 的自身(直接)属性。

  • object Object 要查询的对象。
  • path Array|string 要检查的路径。

→ boolean

var object = { 'a': { 'b': 2 } };
var other = _.create({ 'a': _.create({ 'b': 2 }) });
_.has(object, 'a')
结果 boolean
true
var object = { 'a': { 'b': 2 } };
var other = _.create({ 'a': _.create({ 'b': 2 }) });
_.has(object, 'a.b')
结果 boolean
true
var object = { 'a': { 'b': 2 } };
var other = _.create({ 'a': _.create({ 'b': 2 }) });
_.has(object, ['a', 'b'])
结果 boolean
true
var object = { 'a': { 'b': 2 } };
var other = _.create({ 'a': _.create({ 'b': 2 }) });
_.has(other, 'a')
结果 boolean
false

_.hasIn(object, path)

检查 path 是否为 object 的自身或继承属性。

  • object Object 要查询的对象。
  • path Array|string 要检查的路径。

→ boolean

var object = _.create({ 'a': _.create({ 'b': 2 }) });
_.hasIn(object, 'a')
结果 boolean
true
var object = _.create({ 'a': _.create({ 'b': 2 }) });
_.hasIn(object, 'a.b')
结果 boolean
true
var object = _.create({ 'a': _.create({ 'b': 2 }) });
_.hasIn(object, ['a', 'b'])
结果 boolean
true
var object = _.create({ 'a': _.create({ 'b': 2 }) });
_.hasIn(object, 'b')
结果 boolean
false

_.invert(object)

创建一个键值互换后的 object 新对象。若 object 中有重复的值,后出现的值会覆盖之前的赋值。

  • object Object 要反转键值的对象。

→ Object

var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invert(object)
结果 object
{"1":"c","2":"b"}

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

与 _.invert 类似,但反转后的键由 object 每个元素经 iteratee 处理的结果生成,其值为生成该键的原始键组成的数组。iteratee 调用时传入一个参数:(value)。

  • object Object 要反转键值的对象。
  • iteratee Function 可选 默认值 _.identity 对每个元素调用的 iteratee。

→ Object

var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invertBy(object)
结果 object
{"1":["a","c"],"2":["b"]}
var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invertBy(object, function(value) {
  return 'group' + value;
})
结果 object
{"group1":["a","c"],"group2":["b"]}

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

调用 object 在 path 处的方法。

  • object Object 要查询的对象。
  • path Array|string 要调用的方法路径。
  • args ...* 可选 调用方法时传入的参数。

→ *

var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
_.invoke(object, 'a[0].b.c.slice', 1, 3)
结果 list
[2,3]

_.keys(object)

返回 object 自身可枚举属性名组成的数组。

注意: 非对象值会被强制转换为对象。详见 ES 规范。

  • object Object 要查询的对象。

→ Array

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.keys(new Foo)
结果 list
["a","b"]
function Foo() {
  this.a = 1;
  this.b = 2;
};
_.keys('hi')
结果 list
["0","1"]

_.keysIn(object)

返回 object 自身及继承的可枚举属性名组成的数组。

注意: 非对象值会被强制转换为对象。

  • object Object 要查询的对象。

→ Array

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.keysIn(new Foo)
结果 list
["a","b"]

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

与 _.mapValues 相反:创建一个与 object 值相同的新对象,其键由 object 每个自身可枚举字符串键属性经 iteratee 处理后生成。iteratee 调用时传入三个参数:(value, key, object)。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Object

_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  return key + value;
})
结果 object
{"a1":1,"b2":2}

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

创建一个与 object 键相同的新对象,其值由 object 每个自身可枚举字符串键属性经 iteratee 处理后生成。iteratee 调用时传入三个参数:(value, key, object)。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Object

var users = {
  'fred':    { 'user': 'fred',    'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
};
_.mapValues(users, function(o) { return o.age; })
结果 object
{"fred":40,"pebbles":1}
var users = {
  'fred':    { 'user': 'fred',    'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
};
_.mapValues(users, 'age')
结果 object
{"fred":40,"pebbles":1}

_.merge(object, [sources])

与 _.assign 类似,但会把源对象自身及继承的可枚举字符串键属性递归合并到目标对象。若目标值已存在,源中解析为 undefined 的属性会被跳过。数组和普通对象属性递归合并,其他对象和值类型则直接赋值覆盖。源对象从左到右应用,后面的源会覆盖前面源的同名属性。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 可选 源对象。

→ Object

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};
_.merge(object, other)
结果 object
{"a":[{"b":2,"c":3},{"d":4,"e":5}]}

_.mergeWith(object, sources, customizer)

与 _.merge 类似,但接受一个 customizer 来生成目标属性与源属性合并后的值;若 customizer 返回 undefined,则交由方法本身合并。customizer 调用时传入六个参数:(objValue, srcValue, key, object, source, stack)。

注意: 此方法会修改 object。

  • object Object 目标对象。
  • sources ...Object 源对象。
  • customizer Function 用于自定义赋值结果的函数。

→ 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)
结果 object
{"a":[1,3],"b":[2,4]}

_.omit(object, [paths])

与 _.pick 相反:创建一个由 object 自身及继承的可枚举属性路径组成、但排除了指定路径的新对象。

注意: 此方法明显比 _.pick 慢。

  • object Object 源对象。
  • paths ...(string|string[]) 可选 要排除的属性路径。

→ Object

var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omit(object, ['a', 'c'])
结果 object
{"b":"2"}

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

与 _.pickBy 相反:创建一个由 object 自身及继承的可枚举字符串键属性组成的新对象,仅保留 predicate 未返回真值的属性。predicate 调用时传入两个参数:(value, key)。

  • object Object 源对象。
  • predicate Function 可选 默认值 _.identity 对每个属性调用的函数。

→ Object

var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omitBy(object, _.isNumber)
结果 object
{"b":"2"}

_.pick(object, [paths])

创建一个由 object 中选定属性组成的新对象。

  • object Object 源对象。
  • paths ...(string|string[]) 可选 要选取的属性路径。

→ Object

var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pick(object, ['a', 'c'])
结果 object
{"a":1,"c":3}

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

创建一个新对象,只包含 object 中 predicate 返回真值的属性。predicate 调用时传入两个参数:(value, key)。

  • object Object 源对象。
  • predicate Function 可选 默认值 _.identity 对每个属性调用的函数。

→ Object

var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pickBy(object, _.isNumber)
结果 object
{"a":1,"c":3}

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

与 _.get 类似,但若解析出的值是函数,会以其父对象为 this 调用它并返回调用结果。

  • object Object 要查询的对象。
  • path Array|string 要解析的属性路径。
  • defaultValue * 可选 解析结果为 `undefined` 时返回的值。

→ *

var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
_.result(object, 'a[0].b.c1')
结果 number
3
var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
_.result(object, 'a[0].b.c2')
结果 number
4
var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
_.result(object, 'a[0].b.c3', 'default')
结果 string
"default"
var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
_.result(object, 'a[0].b.c3', _.constant('default'))
结果 string
"default"

_.set(object, path, value)

设置 object 在 path 处的值。若 path 的某部分不存在则自动创建:缺失的索引属性创建为数组,其他缺失属性创建为对象。如需自定义 path 的创建方式,请使用 _.setWith。

注意: 此方法会修改 object。

  • object Object 要修改的对象。
  • path Array|string 要设置的属性路径。
  • value * 要设置的值。

→ Object

var object = { 'a': [{ 'b': { 'c': 3 } }] };
console.log(object.a[0].b.c)
结果 undefined
undefined

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

与 _.set 类似,但接受一个 customizer 来生成 path 上的对象。若 customizer 返回 undefined,则交由方法本身创建路径。customizer 调用时传入三个参数:(nsValue, key, nsObject)。

注意: 此方法会修改 object。

  • object Object 要修改的对象。
  • path Array|string 要设置的属性路径。
  • value * 要设置的值。
  • customizer Function 可选 用于自定义赋值结果的函数。

→ Object

var object = {};
_.setWith(object, '[0][1]', 'a', Object)
结果 object
{"0":{"1":"a"}}

_.toPairs(object)

返回 object 自身可枚举字符串键的键值对数组,可供 _.fromPairs 使用。若 object 是 Map 或 Set,则返回其条目(entries)。

  • object Object 要查询的对象。

→ Array

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.toPairs(new Foo)
结果 list
[["a",1],["b",2]]

_.toPairsIn(object)

返回 object 自身及继承的可枚举字符串键的键值对数组,可供 _.fromPairs 使用。若 object 是 Map 或 Set,则返回其条目(entries)。

  • object Object 要查询的对象。

→ Array

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.toPairsIn(new Foo)
结果 list
[["a",1],["b",2]]

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

_.reduce 的替代方案:对 object 的每个自身可枚举字符串键属性调用 iteratee,把结果累积到新的 accumulator 对象中,每次调用都可以直接修改 accumulator。若未提供 accumulator,则使用一个具有相同 [[Prototype]] 的新对象。iteratee 调用时传入四个参数:(accumulator, value, key, object)。iteratee 显式返回 false 可提前结束遍历。

  • object Object 要遍历的对象。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。
  • accumulator * 可选 自定义的累加器初始值。

→ *

_.transform([2, 3, 4], function(result, n) {
  result.push(n *= n);
  return n % 2 == 0;
}, [])
结果 list
[4,9]
_.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
}, {})
结果 object
{"1":["a","c"],"2":["b"]}

_.unset(object, path)

移除 object 在 path 处的属性。

注意: 此方法会修改 object。

  • object Object 要修改的对象。
  • path Array|string 要移除的属性路径。

→ boolean

var object = { 'a': [{ 'b': { 'c': 7 } }] };
_.unset(object, 'a[0].b.c')
结果 boolean
true
var object = { 'a': [{ 'b': { 'c': 7 } }] };
console.log(object)
结果 undefined
undefined
var object = { 'a': [{ 'b': { 'c': 7 } }] };
_.unset(object, ['a', '0', 'b', 'c'])
结果 boolean
true
var object = { 'a': [{ 'b': { 'c': 7 } }] };
console.log(object)
结果 undefined
undefined

_.update(object, path, updater)

与 _.set 类似,但接受一个 updater 来生成要设置的值。如需自定义 path 的创建方式,请使用 _.updateWith。updater 调用时传入一个参数:(value)。

注意: 此方法会修改 object。

  • object Object 要修改的对象。
  • path Array|string 要设置的属性路径。
  • updater Function 生成更新后值的函数。

→ Object

var object = { 'a': [{ 'b': { 'c': 3 } }] };
console.log(object.a[0].b.c)
结果 undefined
undefined

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

与 _.update 类似,但接受一个 customizer 来生成 path 上的对象。若 customizer 返回 undefined,则交由方法本身创建路径。customizer 调用时传入三个参数:(nsValue, key, nsObject)。

注意: 此方法会修改 object。

  • object Object 要修改的对象。
  • path Array|string 要设置的属性路径。
  • updater Function 生成更新后值的函数。
  • customizer Function 可选 用于自定义赋值结果的函数。

→ Object

var object = {};
_.updateWith(object, '[0][1]', _.constant('a'), Object)
结果 object
{"0":{"1":"a"}}

_.values(object)

返回 object 自身可枚举字符串键属性的值组成的数组。

注意: 非对象值会被强制转换为对象。

  • object Object 要查询的对象。

→ Array

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.values(new Foo)
结果 list
[1,2]
function Foo() {
  this.a = 1;
  this.b = 2;
};
_.values('hi')
结果 list
["h","i"]

_.valuesIn(object)

返回 object 自身及继承的可枚举字符串键属性的值组成的数组。

注意: 非对象值会被强制转换为对象。

  • object Object 要查询的对象。

→ Array

function Foo() {
  this.a = 1;
  this.b = 2;
};
_.valuesIn(new Foo)
结果 list
[1,2]

Seq

_.chain(value)

创建一个包装 value 的 lodash 包装器实例,并启用显式方法链。链式调用的结果必须通过 _#value 解包。

  • value * 要包装的值。

→ Object

_.tap(value, interceptor)

调用 interceptor 并返回 value。interceptor 调用时传入一个参数:(value)。此方法用于“切入”方法链,以修改中间结果。

  • value * 传给 `interceptor` 的值。
  • interceptor Function 要调用的函数。

→ *

_([1, 2, 3])
 .tap(function(array) {
   array.pop();
 })
 .reverse()
 .value()
结果 list
[2,1]

_.thru(value, interceptor)

与 _.tap 类似,但返回 interceptor 的结果。此方法用于在方法链中“透传”值,替换中间结果。

  • value * 传给 `interceptor` 的值。
  • interceptor Function 要调用的函数。

→ *

_('  abc  ')
 .chain()
 .trim()
 .thru(function(value) {
   return [value];
 })
 .value()
结果 list
["abc"]

String

_.camelCase([string=''])

将 string 转换为 驼峰命名(camel case)。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.camelCase('Foo Bar')
结果 string
"fooBar"
_.camelCase('--foo-bar--')
结果 string
"fooBar"
_.camelCase('__FOO_BAR__')
结果 string
"fooBar"

_.capitalize([string=''])

将 string 的首字母转为大写,其余字符转为小写。

  • string string 可选 默认值 '' 要首字母大写的字符串。

→ string

_.capitalize('FRED')
结果 string
"Fred"

_.deburr([string=''])

去除 string 中的变音符号:把 Latin-1 补充 和 拉丁文扩展-A 字母转换为基本拉丁字母,并移除 组合用变音符号。

  • string string 可选 默认值 '' 要去除变音符号的字符串。

→ string

_.deburr('déjà vu')
结果 string
"deja vu"

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

检查 string 是否以给定的目标字符串结尾。

  • string string 可选 默认值 '' 要检查的字符串。
  • target string 可选 要查找的字符串。
  • position number 可选 默认值 string.length 查找截止的位置。

→ boolean

_.endsWith('abc', 'c')
结果 boolean
true
_.endsWith('abc', 'b')
结果 boolean
false
_.endsWith('abc', 'b', 2)
结果 boolean
true

_.escape([string=''])

把 string 中的 &、<、>、" 和 ' 转换为对应的 HTML 实体。

注意: 不会转义其他字符。如需转义更多字符,请使用 he 等第三方库。

> 出于对称性而被转义;但 > 和 / 在 HTML 中本无需转义,除非出现在标签或未加引号的属性值中才有特殊含义。详见 Mathias Bynens 的文章(“semi-related fun fact”一节)。

处理 HTML 时,应始终 为属性值加引号 以减少 XSS 攻击面。

  • string string 可选 默认值 '' 要转义的字符串。

→ string

_.escape('fred, barney, & pebbles')
结果 string
"fred, barney, &amp; pebbles"

_.escapeRegExp([string=''])

转义 string 中的 RegExp 特殊字符:^、$、\、.、*、+、?、(、)、[、]、{、} 和 |。

  • string string 可选 默认值 '' 要转义的字符串。

→ string

_.escapeRegExp('[lodash](https://lodash.com/)')
结果 string
"\\[lodash\\]\\(https://lodash\\.com/\\)"

_.kebabCase([string=''])

将 string 转换为 短横线命名(kebab case)。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.kebabCase('Foo Bar')
结果 string
"foo-bar"
_.kebabCase('fooBar')
结果 string
"foo-bar"
_.kebabCase('__FOO_BAR__')
结果 string
"foo-bar"

_.lowerCase([string=''])

将 string 转换为以空格分隔的小写单词。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.lowerCase('--Foo-Bar--')
结果 string
"foo bar"
_.lowerCase('fooBar')
结果 string
"foo bar"
_.lowerCase('__FOO_BAR__')
结果 string
"foo bar"

_.lowerFirst([string=''])

将 string 的首字符转为小写。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.lowerFirst('Fred')
结果 string
"fred"
_.lowerFirst('FRED')
结果 string
"fRED"

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

若 string 短于 length,在其左右两侧填充。若填充字符无法被均分,会被截断。

  • string string 可选 默认值 '' 要填充的字符串。
  • length number 可选 默认值 0 填充后的目标长度。
  • chars string 可选 默认值 ' ' 用作填充的字符串。

→ string

_.pad('abc', 8)
结果 string
"  abc   "
_.pad('abc', 8, '_-')
结果 string
"_-abc_-_"
_.pad('abc', 3)
结果 string
"abc"

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

若 string 短于 length,在其右侧填充;超出 length 的填充字符会被截断。

  • string string 可选 默认值 '' 要填充的字符串。
  • length number 可选 默认值 0 填充后的目标长度。
  • chars string 可选 默认值 ' ' 用作填充的字符串。

→ string

_.padEnd('abc', 6)
结果 string
"abc   "
_.padEnd('abc', 6, '_-')
结果 string
"abc_-_"
_.padEnd('abc', 3)
结果 string
"abc"

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

若 string 短于 length,在其左侧填充;超出 length 的填充字符会被截断。

  • string string 可选 默认值 '' 要填充的字符串。
  • length number 可选 默认值 0 填充后的目标长度。
  • chars string 可选 默认值 ' ' 用作填充的字符串。

→ string

_.padStart('abc', 6)
结果 string
"   abc"
_.padStart('abc', 6, '_-')
结果 string
"_-_abc"
_.padStart('abc', 3)
结果 string
"abc"

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

按指定进制把 string 转换为整数。若 radix 为 undefined 或 0,默认按 10 进制解析;但若 value 是十六进制形式,则按 16 进制解析。

注意: 此方法与 parseInt 的 ES5 实现 保持一致。

  • string string 要转换的字符串。
  • radix number 可选 默认值 10 解析 `value` 所用的进制。

→ number

_.parseInt('08')
结果 number
8
_.map(['6', '08', '10'], _.parseInt)
结果 list
[6,8,10]

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

将给定字符串重复 n 次。

  • string string 可选 默认值 '' 要重复的字符串。
  • n number 可选 默认值 1 字符串重复的次数。

→ string

_.repeat('*', 3)
结果 string
"***"
_.repeat('abc', 2)
结果 string
"abcabc"
_.repeat('abc', 0)
结果 string
""

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

将 string 中匹配 pattern 的部分替换为 replacement。

注意: 此方法基于 String#replace。

  • string string 可选 默认值 '' 要修改的字符串。
  • pattern RegExp|string 要替换的模式。
  • replacement Function|string 用于替换匹配内容的值。

→ string

_.replace('Hi Fred', 'Fred', 'Barney')
结果 string
"Hi Barney"

_.snakeCase([string=''])

将 string 转换为 下划线命名(snake case)。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.snakeCase('Foo Bar')
结果 string
"foo_bar"
_.snakeCase('fooBar')
结果 string
"foo_bar"
_.snakeCase('--FOO-BAR--')
结果 string
"foo_bar"

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

按 separator 拆分 string。

注意: 此方法基于 String#split。

  • string string 可选 默认值 '' 要拆分的字符串。
  • separator RegExp|string 用于拆分的分隔符模式。
  • limit number 可选 结果截断的长度上限。

→ Array

_.split('a-b-c', '-', 2)
结果 list
["a","b"]

_.startCase([string=''])

将 string 转换为 首字母大写的空格分隔形式(start case)。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.startCase('--foo-bar--')
结果 string
"Foo Bar"
_.startCase('fooBar')
结果 string
"Foo Bar"
_.startCase('__FOO_BAR__')
结果 string
"FOO BAR"

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

检查 string 是否以给定的目标字符串开头。

  • string string 可选 默认值 '' 要检查的字符串。
  • target string 可选 要查找的字符串。
  • position number 可选 默认值 0 开始查找的位置。

→ boolean

_.startsWith('abc', 'a')
结果 boolean
true
_.startsWith('abc', 'b')
结果 boolean
false
_.startsWith('abc', 'b', 1)
结果 boolean
true

_.template([string=''], [options={}], [options.escape=_.templateSettings.escape], [options.evaluate=_.templateSettings.evaluate], [options.imports=_.templateSettings.imports], [options.interpolate=_.templateSettings.interpolate], [options.sourceURL='templateSources[n], [options.variable='obj'])

创建一个编译后的模板函数:可在 “interpolate” 分隔符中插值数据属性,在 “escape” 分隔符中对插值做 HTML 转义,并在 “evaluate” 分隔符中执行 JavaScript。模板中可将数据属性作为自由变量访问。若传入设置对象,其优先级高于 _.templateSettings。

安全: _.template 不安全,不应使用,并将在 Lodash v5 中移除。避免处理不可信输入。参见 威胁模型。

注意: 在开发构建中,_.template 使用 sourceURLs 以便调试。

关于预编译模板,参见 lodash 自定义构建文档。

关于 Chrome 扩展沙箱,参见 Chrome 扩展文档。

  • string string 可选 默认值 '' 模板字符串。
  • options Object 可选 默认值 {} 选项对象。
  • options.escape RegExp 可选 默认值 _.templateSettings.escape HTML “escape” 分隔符。
  • options.evaluate RegExp 可选 默认值 _.templateSettings.evaluate “evaluate” 分隔符。
  • options.imports Object 可选 默认值 _.templateSettings.imports 作为自由变量导入模板的对象。
  • options.interpolate RegExp 可选 默认值 _.templateSettings.interpolate “interpolate” 分隔符。
  • options.sourceURL string 可选 默认值 'templateSources[n 编译后模板的 sourceURL。
  • options.variable string 可选 默认值 'obj' 数据对象的变量名。

→ Function

var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' })
结果 string
"hello fred!"
var compiled = _.template('hello <%= user %>!');
var compiled = _.template('<b><%- value %></b>');
compiled({ 'value': '<script>' })
结果 string
"<b>&lt;script&gt;</b>"
var compiled = _.template('hello <%= user %>!');
var compiled = _.template('<b><%- value %></b>');
var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
compiled({ 'users': ['fred', 'barney'] })
结果 string
"<li>fred</li><li>barney</li>"
var compiled = _.template('hello <%= user %>!');
var compiled = _.template('<b><%- value %></b>');
var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
var compiled = _.template('<% print("hello " + user); %>!');
compiled({ 'user': 'barney' })
结果 string
"hello barney!"

_.toLower([string=''])

将 string 整体转换为小写,与 String#toLowerCase 相同。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.toLower('--Foo-Bar--')
结果 string
"--foo-bar--"
_.toLower('fooBar')
结果 string
"foobar"
_.toLower('__FOO_BAR__')
结果 string
"__foo_bar__"

_.toUpper([string=''])

将 string 整体转换为大写,与 String#toUpperCase 相同。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.toUpper('--foo-bar--')
结果 string
"--FOO-BAR--"
_.toUpper('fooBar')
结果 string
"FOOBAR"
_.toUpper('__foo_bar__')
结果 string
"__FOO_BAR__"

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

去除 string 首尾的空白字符或指定字符。

  • string string 可选 默认值 '' 要去除首尾字符的字符串。
  • chars string 可选 默认值 whitespace 要去除的字符。

→ string

_.trim('  abc  ')
结果 string
"abc"
_.trim('-_-abc-_-', '_-')
结果 string
"abc"
_.map(['  foo  ', '  bar  '], _.trim)
结果 list
["foo","bar"]

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

去除 string 末尾的空白字符或指定字符。

  • string string 可选 默认值 '' 要去除首尾字符的字符串。
  • chars string 可选 默认值 whitespace 要去除的字符。

→ string

_.trimEnd('  abc  ')
结果 string
"  abc"
_.trimEnd('-_-abc-_-', '_-')
结果 string
"-_-abc"

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

去除 string 开头的空白字符或指定字符。

  • string string 可选 默认值 '' 要去除首尾字符的字符串。
  • chars string 可选 默认值 whitespace 要去除的字符。

→ string

_.trimStart('  abc  ')
结果 string
"abc  "
_.trimStart('-_-abc-_-', '_-')
结果 string
"abc-_-"

_.truncate([string=''], [options={}], [options.length=30], [options.omission='...'], [options.separator])

若 string 超过给定的最大长度则截断,截断后末尾的字符替换为省略符,默认为 "..."。

  • string string 可选 默认值 '' 要截断的字符串。
  • options Object 可选 默认值 {} 选项对象。
  • options.length number 可选 默认值 30 字符串的最大长度。
  • options.omission string 可选 默认值 '...' 表示文本被省略的字符串。
  • options.separator RegExp|string 可选 截断时对齐的分隔符模式。

→ string

_.truncate('hi-diddly-ho there, neighborino')
结果 string
"hi-diddly-ho there, neighbo..."
_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
})
结果 string
"hi-diddly-ho there,..."
_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': /,? +/
})
结果 string
"hi-diddly-ho there..."
_.truncate('hi-diddly-ho there, neighborino', {
  'omission': ' [...]'
})
结果 string
"hi-diddly-ho there, neig [...]"

_.unescape([string=''])

_.escape 的逆操作:把 string 中的 HTML 实体 &amp;、&lt;、&gt;、&quot; 和 &#39; 转换回对应字符。

注意: 不会反转义其他 HTML 实体。如需处理更多实体,请使用 he 等第三方库。

  • string string 可选 默认值 '' 要反转义的字符串。

→ string

_.unescape('fred, barney, &amp; pebbles')
结果 string
"fred, barney, & pebbles"

_.upperCase([string=''])

将 string 转换为以空格分隔的大写单词。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.upperCase('--foo-bar')
结果 string
"FOO BAR"
_.upperCase('fooBar')
结果 string
"FOO BAR"
_.upperCase('__foo_bar__')
结果 string
"FOO BAR"

_.upperFirst([string=''])

将 string 的首字符转为大写。

  • string string 可选 默认值 '' 要转换的字符串。

→ string

_.upperFirst('fred')
结果 string
"Fred"
_.upperFirst('FRED')
结果 string
"FRED"

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

将 string 拆分为由单词组成的数组。

  • string string 可选 默认值 '' 要检查的字符串。
  • pattern RegExp|string 可选 匹配单词的模式。

→ Array

_.words('fred, barney, & pebbles')
结果 list
["fred","barney","pebbles"]
_.words('fred, barney, & pebbles', /[^, ]+/g)
结果 list
["fred","barney","&","pebbles"]

Util

_.attempt(func, [args])

尝试调用 func,返回调用结果或捕获到的错误对象。额外传入的参数会在调用时转交给 func。

  • func Function 要尝试调用的函数。
  • args ...* 可选 调用 `func` 时传入的参数。

→ *

_.bindAll(object, methodNames)

把对象的方法绑定到对象自身,并覆盖原有方法。

注意: 此方法不会设置绑定函数的 length 属性。

  • object Object 要绑定方法并写回绑定结果的对象。
  • methodNames ...(string|string[]) 要绑定的方法名。

→ Object

_.cond(pairs)

创建一个函数,遍历 pairs,找到第一个返回真值的断言函数后调用与之配对的函数。断言函数与处理函数均以所创建函数的 this 绑定和参数调用。

  • pairs Array 由“断言函数 - 处理函数”组成的配对数组。

→ Function

var func = _.cond([
  [_.matches({ 'a': 1 }),           _.constant('matches A')],
  [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
  [_.stubTrue,                      _.constant('no match')]
]);
func({ 'a': 1, 'b': 2 })
结果 string
"matches A"
var func = _.cond([
  [_.matches({ 'a': 1 }),           _.constant('matches A')],
  [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
  [_.stubTrue,                      _.constant('no match')]
]);
func({ 'a': 0, 'b': 1 })
结果 string
"matches B"
var func = _.cond([
  [_.matches({ 'a': 1 }),           _.constant('matches A')],
  [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
  [_.stubTrue,                      _.constant('no match')]
]);
func({ 'a': '1', 'b': '2' })
结果 string
"no match"

_.conforms(source)

创建一个函数:用 source 中的断言属性逐一检查给定对象对应的属性值,全部返回真值时返回 true,否则返回 false。

注意: 所创建的函数等价于部分应用了 source 的 _.conformsTo。

  • source Object 由属性断言函数组成、需要满足的对象。

→ Function

var objects = [
  { 'a': 2, 'b': 1 },
  { 'a': 1, 'b': 2 }
];
_.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }))
结果 list
[{"a":1,"b":2}]

_.constant(value)

创建一个始终返回 value 的函数。

  • value * 新函数要返回的值。

→ Function

var objects = _.times(2, _.constant({ 'a': 1 }));
console.log(objects)
结果 undefined
undefined
var objects = _.times(2, _.constant({ 'a': 1 }));
console.log(objects[0] === objects[1])
结果 undefined
undefined

_.defaultTo(value, defaultValue)

检查 value,决定是否用默认值替代它:当 value 为 NaN、null 或 undefined 时返回 defaultValue。

  • value * 要检查的值。
  • defaultValue * 默认值。

→ *

_.defaultTo(1, 10)
结果 number
1
_.defaultTo(undefined, 10)
结果 number
10

_.flow([funcs])

创建一个函数,以该函数的 this 绑定依次调用给定的函数,每次调用都接收上一次调用的返回值,最终返回最后一个函数的结果。

  • funcs ...(Function|Function[]) 可选 要调用的函数。

→ Function

function square(n) {
  return n * n;
};
var addSquare = _.flow([_.add, square]);
addSquare(1, 2)
结果 number
9

_.flowRight([funcs])

与 _.flow 类似,但创建的函数从右向左调用给定的函数。

  • funcs ...(Function|Function[]) 可选 要调用的函数。

→ Function

function square(n) {
  return n * n;
};
var addSquare = _.flowRight([square, _.add]);
addSquare(1, 2)
结果 number
9

_.identity(value)

返回接收到的第一个参数。

  • value * 任意值。

→ *

var object = { 'a': 1 };
console.log(_.identity(object) === object)
结果 undefined
undefined

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

创建一个以其接收的参数调用 func 的函数。若 func 是属性名,所创建的函数返回给定元素的该属性值;若 func 是数组或对象,所创建的函数对包含等价源属性的元素返回 true,否则返回 false。

  • func * 可选 默认值 _.identity 要转换为回调函数的值。

→ Function

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(users, _.iteratee({ 'user': 'barney', 'active': true }))
结果 list
[{"user":"barney","age":36,"active":true}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(users, _.iteratee(['user', 'fred']))
结果 list
[{"user":"fred","age":40,"active":false}]
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.map(users, _.iteratee('user'))
结果 list
["barney","fred"]
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.filter(['abc', 'def'], /ef/)
结果 list
["abc","def"]

_.matches(source)

创建一个函数,对给定对象与 source 做部分深度比较:若给定对象具有等价的属性值则返回 true,否则返回 false。

注意: 所创建的函数等价于部分应用了 source 的 _.isMatch。

部分比较时,source 中的空数组和空对象分别与任意数组和对象值匹配。支持的比较类型见 _.isEqual。

注意: 可用 _.overSome 组合多个匹配器来检查多个值。

  • source Object 用于匹配的属性值对象。

→ Function

var objects = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 6 }
];
_.filter(objects, _.matches({ 'a': 4, 'c': 6 }))
结果 list
[{"a":4,"b":5,"c":6}]
var objects = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 6 }
];
_.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]))
结果 list
[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6}]

_.matchesProperty(path, srcValue)

创建一个函数,对给定对象在 path 处的值与 srcValue 做部分深度比较:等价时返回 true,否则返回 false。

注意: 部分比较时,srcValue 中的空数组和空对象分别与任意数组和对象值匹配。支持的比较类型见 _.isEqual。

注意: 可用 _.overSome 组合多个匹配器来检查多个值。

  • path Array|string 要获取的属性路径。
  • srcValue * 要匹配的值。

→ Function

var objects = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 6 }
];
_.find(objects, _.matchesProperty('a', 4))
结果 object
{"a":4,"b":5,"c":6}
var objects = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 6 }
];
_.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]))
结果 list
[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6}]

_.method(path, [args])

创建一个函数,调用给定对象在 path 处的方法。额外参数会传给被调用的方法。

  • path Array|string 要调用的方法路径。
  • args ...* 可选 调用方法时传入的参数。

→ Function

var objects = [
  { 'a': { 'b': _.constant(2) } },
  { 'a': { 'b': _.constant(1) } }
];
_.map(objects, _.method('a.b'))
结果 list
[2,1]
var objects = [
  { 'a': { 'b': _.constant(2) } },
  { 'a': { 'b': _.constant(1) } }
];
_.map(objects, _.method(['a', 'b']))
结果 list
[2,1]

_.methodOf(object, [args])

与 _.method 相反:创建一个函数,调用 object 在给定路径处的方法。额外参数会传给被调用的方法。

  • object Object 要查询的对象。
  • args ...* 可选 调用方法时传入的参数。

→ Function

var array = _.times(3, _.constant),
    object = { 'a': array, 'b': array, 'c': array };
_.map(['a[2]', 'c[0]'], _.methodOf(object))
结果 list
[2,0]
var array = _.times(3, _.constant),
    object = { 'a': array, 'b': array, 'c': array };
_.map([['a', '2'], ['c', '0']], _.methodOf(object))
结果 list
[2,0]

_.noop()

始终返回 undefined。

_.times(2, _.noop)
结果 list
[null,null]

_.nthArg([n=0])

创建一个函数,返回索引为 n 的参数;n 为负数时返回倒数第 n 个参数。

  • n number 可选 默认值 0 要返回的参数索引。

→ Function

var func = _.nthArg(1);
func('a', 'b', 'c', 'd')
结果 string
"b"
var func = _.nthArg(1);
var func = _.nthArg(-2);
func('a', 'b', 'c', 'd')
结果 string
"c"

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

创建一个函数,以其接收的参数调用各个 iteratees,并返回结果组成的数组。

  • iteratees ...(Function|Function[]) 可选 默认值 [_.identity 要调用的 iteratee。

→ Function

var func = _.over([Math.max, Math.min]);
func(1, 2, 3, 4)
结果 list
[4,1]

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

创建一个函数,检查以其接收的参数调用时,predicates 是否全部返回真值。

断言支持以下简写:传入 Object 时,将其作为 _.matches 的参数生成断言;传入 Array 时,将其作为 _.matchesProperty 的参数生成断言。

  • predicates ...(Function|Function[]) 可选 默认值 [_.identity 要检查的断言函数(predicate)。

→ Function

var func = _.overEvery([Boolean, isFinite]);
func('1')
结果 boolean
true
var func = _.overEvery([Boolean, isFinite]);
func(null)
结果 boolean
false
var func = _.overEvery([Boolean, isFinite]);
func(NaN)
结果 boolean
false

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

创建一个函数,检查以其接收的参数调用时,predicates 中是否任一返回真值。

断言支持以下简写:传入 Object 时,将其作为 _.matches 的参数生成断言;传入 Array 时,将其作为 _.matchesProperty 的参数生成断言。

  • predicates ...(Function|Function[]) 可选 默认值 [_.identity 要检查的断言函数(predicate)。

→ Function

var func = _.overSome([Boolean, isFinite]);
func('1')
结果 boolean
true
var func = _.overSome([Boolean, isFinite]);
func(null)
结果 boolean
true
var func = _.overSome([Boolean, isFinite]);
func(NaN)
结果 boolean
false

_.property(path)

创建一个函数,返回给定对象在 path 处的值。

  • path Array|string 要获取的属性路径。

→ Function

var objects = [
  { 'a': { 'b': 2 } },
  { 'a': { 'b': 1 } }
];
_.map(objects, _.property('a.b'))
结果 list
[2,1]
var objects = [
  { 'a': { 'b': 2 } },
  { 'a': { 'b': 1 } }
];
_.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b')
结果 list
[1,2]

_.propertyOf(object)

与 _.property 相反:创建一个函数,返回 object 在给定路径处的值。

  • object Object 要查询的对象。

→ Function

var array = [0, 1, 2],
    object = { 'a': array, 'b': array, 'c': array };
_.map(['a[2]', 'c[0]'], _.propertyOf(object))
结果 list
[2,0]
var array = [0, 1, 2],
    object = { 'a': array, 'b': array, 'c': array };
_.map([['a', '2'], ['c', '0']], _.propertyOf(object))
结果 list
[2,0]

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

创建一个从 start 递进到 end(不含)的数字数组(可为正数或负数)。若只指定了负数 start 而未指定 end 或 step,步长为 -1。若未指定 end,则把 start 作为 end,并将 start 设为 0。

注意: JavaScript 采用 IEEE-754 标准处理浮点数,可能产生意料之外的结果。

  • start number 可选 默认值 0 范围的起始值。
  • end number 范围的结束值。
  • step number 可选 默认值 1 每步递增或递减的值。

→ Array

_.range(4)
结果 list
[0,1,2,3]
_.range(-4)
结果 list
[0,-1,-2,-3]
_.range(1, 5)
结果 list
[1,2,3,4]
_.range(0, 20, 5)
结果 list
[0,5,10,15]

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

与 _.range 类似,但按降序生成数值。

  • start number 可选 默认值 0 范围的起始值。
  • end number 范围的结束值。
  • step number 可选 默认值 1 每步递增或递减的值。

→ Array

_.rangeRight(4)
结果 list
[3,2,1,0]
_.rangeRight(-4)
结果 list
[-3,-2,-1,0]
_.rangeRight(1, 5)
结果 list
[4,3,2,1]
_.rangeRight(0, 20, 5)
结果 list
[15,10,5,0]

_.stubArray()

返回一个新的空数组。

→ Array

var arrays = _.times(2, _.stubArray);
console.log(arrays)
结果 undefined
undefined
var arrays = _.times(2, _.stubArray);
console.log(arrays[0] === arrays[1])
结果 undefined
undefined

_.stubFalse()

返回 false。

→ boolean

_.times(2, _.stubFalse)
结果 list
[false,false]

_.stubObject()

返回一个新的空对象。

→ Object

var objects = _.times(2, _.stubObject);
console.log(objects)
结果 undefined
undefined
var objects = _.times(2, _.stubObject);
console.log(objects[0] === objects[1])
结果 undefined
undefined

_.stubString()

返回空字符串。

→ string

_.times(2, _.stubString)
结果 list
["",""]

_.stubTrue()

返回 true。

→ boolean

_.times(2, _.stubTrue)
结果 list
[true,true]

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

调用 iteratee n 次,返回每次调用结果组成的数组。iteratee 调用时传入一个参数:(index)。

  • n number 调用 `iteratee` 的次数。
  • iteratee Function 可选 默认值 _.identity 每次迭代时调用的函数。

→ Array

_.times(3, String)
结果 list
["0","1","2"]
_.times(4, _.constant(0))
结果 list
[0,0,0,0]

_.toPath(value)

将 value 转换为属性路径数组。

  • value * 要转换的值。

→ Array

_.toPath('a.b.c')
结果 list
["a","b","c"]
_.toPath('a[0].b.c')
结果 list
["a","0","b","c"]

_.uniqueId([prefix=''])

生成一个唯一 ID;若提供 prefix,ID 会追加在其后。

  • prefix string 可选 默认值 '' ID 的前缀。

→ string

_.uniqueId('contact_')
结果 string
"contact_1"
_.uniqueId()
结果 string
"2"

别名

_.each → _.forEach _.eachRight → _.forEachRight _.entries → _.toPairs _.entriesIn → _.toPairsIn _.extend → _.assignIn _.extendWith → _.assignInWith _.first → _.head

安装智能体工具

为你的编程智能体接入 Sommatic AI 官方文档:技能包、文档 MCP 服务器与 Markdown 页面,无需再抓取网页。

安装 Sommatic AI CLI,并为检测到的智能体配置合适的插件。

npx @sommatic/cli agent setup
智能体如何读取本文档