数组

集合

日期

函数

语言

数学

数字

对象

序列

字符串

工具

属性

方法

“数组” 方法

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

源代码 npm 包

将数组(array)拆分为多个 size 长度的区块,并将这些区块组成一个新数组。 如果数组(array)无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。

3.0.0

参数

  1. array (Array): 需要处理的数组
  2. [size=1] (number): 每个区块的长度

返回值

(Array): 返回一个包含区块的新数组(array)。

例子

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
 
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

_.compact(array)

源代码 npm 包

创建一个移除了所有假值的数组。例如:false、null、0、""、undefined 和 NaN 都是假值。

0.1.0

参数

  1. array (Array): 待压缩的数组

返回值

(Array): 返回过滤掉假值后的新数组

例子

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

_.concat(array, [values])

源代码 npm 包

创建一个新数组,将 array 与任何其他数组和/或值连接在一起。

4.0.0

参数

  1. array (Array): 被连接的数组。
  2. [values] (...*): 连接的值。

返回值

(Array): 返回连接后的新数组。

例子

var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
 
console.log(other);
// => [1, 2, 3, [4]]
 
console.log(array);
// => [1]

_.difference(array, [values])

源代码 npm 包

创建一个具有唯一 array 值的新数组,每个值不包含在其他给定的数组中。(使用 SameValueZero 做相等比较)。结果值的顺序和引用由第一个数组确定。

**注意:** 不像 _.pullAll,这个方法会返回一个新数组。

0.1.0

参数

  1. array (Array): 要检查的数组。
  2. [values] (...Array): 排除的值。

返回值

(Array): 返回过滤掉假值后的新数组

例子

_.difference([2, 1], [2, 3]);
// => [1]

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

源代码 npm 包

这个方法类似 _.difference ,除了它接受一个 iteratee (迭代函数),调用 array 和 values 中的每个元素以生成比较的标准。 结果值的顺序和引用由第一个数组确定。 iteratee 调用一个参数:
(value).

**注意:** 不像 _.pullAllBy,这个方法会返回一个新数组。

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. [values] (...Array): 排除的值。
  3. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(Array): 返回过滤掉假值后的新数组

例子

_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [1.2]
 
// The `_.property` iteratee shorthand.
_.differenceBy([{ 'x'2 }, { 'x'1 }], [{ 'x'1 }], 'x');
// => [{ 'x': 2 }]

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

源代码 npm 包

此方法类似于 _.difference,不同之处在于它接受 comparator,它调用比较 array 中的元素和 values。结果值的顺序和引用由第一个数组确定。comparator 调用两个参数:(arrVal, othVal)。

**注意:** 不像 _.pullAllWith,此方法返回一个新数组。

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. [values] (...Array): 排除的值。
  3. [comparator] (Function): 每个元素调用的比较函数。

返回值

(Array): 返回过滤掉假值后的新数组

例子

var objects = [{ 'x'1, 'y'2 }, { 'x'2, 'y'1 }];
 
_.differenceWith(objects, [{ 'x'1, 'y'2 }], _.isEqual);
// => [{ 'x': 2, 'y': 1 }]

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

源代码 npm 包

创建一个数组切片,从 array 的开头移除 n 个元素。

0.5.0

参数

  1. array (Array): 要查询的数组。
  2. [n=1] (number): 要移除的元素个数。

返回值

(Array): 返回 array 的切片。

例子

_.drop([1, 2, 3]);
// => [2, 3]
 
_.drop([1, 2, 3], 2);
// => [3]
 
_.drop([1, 2, 3], 5);
// => []
 
_.drop([1, 2, 3], 0);
// => [1, 2, 3]

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

源代码 npm 包

创建一个数组切片,从 array 的末尾移除 n 个元素。

3.0.0

参数

  1. array (Array): 要查询的数组。
  2. [n=1] (number): 要移除的元素个数。

返回值

(Array): 返回 array 的切片。

例子

_.dropRight([1, 2, 3]);
// => [1, 2]
 
_.dropRight([1, 2, 3], 2);
// => [1]
 
_.dropRight([1, 2, 3], 5);
// => []
 
_.dropRight([1, 2, 3], 0);
// => [1, 2, 3]

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

源代码 npm 包

创建一个切片数组,去除 array 中从 predicate 返回假值开始到 array 末尾的所有元素。predicate 调用三个参数: (value, index, array)。

3.0.0

参数

  1. array (Array): 要查询的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(Array): 返回 array 的切片。

例子

var users = [
  { 'user''barney',  'active': true },
  { 'user''fred',    'active': false },
  { 'user''pebbles', 'active': false }
];
 
_.dropRightWhile(users, function(o) { return !o.active; });
// => objects for ['barney']
 
// The `_.matches` iteratee shorthand.
_.dropRightWhile(users, { 'user''pebbles', 'active': false });
// => objects for ['barney', 'fred']
 
// The `_.matchesProperty` iteratee shorthand.
_.dropRightWhile(users, ['active', false]);
// => objects for ['barney']
 
// The `_.property` iteratee shorthand.
_.dropRightWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']

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

源代码 npm 包

创建一个数组切片,去除 array 中从起点开始到 predicate 返回假值结束部分。predicate 调用三个参数: (value, index, array)。

3.0.0

参数

  1. array (Array): 要查询的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(Array): 返回 array 的切片。

例子

var users = [
  { 'user''barney',  'active': false },
  { 'user''fred',    'active': false },
  { 'user''pebbles', 'active': true }
];
 
_.dropWhile(users, function(o) { return !o.active; });
// => objects for ['pebbles']
 
// The `_.matches` iteratee shorthand.
_.dropWhile(users, { 'user''barney', 'active': false });
// => objects for ['fred', 'pebbles']
 
// The `_.matchesProperty` iteratee shorthand.
_.dropWhile(users, ['active', false]);
// => objects for ['pebbles']
 
// The `_.property` iteratee shorthand.
_.dropWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']

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

源代码 npm 包

使用 value 值来填充(替换) array 中从 start 位置开始到 end 位置结束(不包含 end 位置)的所有元素。

**注意:** 这个方法会改变 array。

3.2.0

参数

  1. array (Array): 待填充改变的数组。
  2. value (*): 填充给 array 的值。
  3. [start=0] (number): 开始位置(默认 0)。
  4. [end=array.length] (number): 结束位置(默认 array.length)。

返回值

(Array): 返回 array。

例子

var array = [1, 2, 3];
 
_.fill(array, 'a');
console.log(array);
// => ['a', 'a', 'a']
 
_.fill(Array(3), 2);
// => [2, 2, 2]
 
_.fill([4, 6, 8, 10], '*', 1, 3);
// => [4, '*', '*', 10]

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

源代码 npm 包

该方法类似于 _.find,不同之处在于它返回 predicate 返回 truthy 的第一个元素的索引,而不是元素本身。

1.1.0

参数

  1. array (Array): 要检查的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。
  3. [fromIndex=0] (number): 开始搜索的索引值。

返回值

(number): 返回找到元素的索引值,否则返回 -1。

例子

var users = [
  { 'user''barney',  'active': false },
  { 'user''fred',    'active': false },
  { 'user''pebbles', 'active': true }
];
 
_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0
 
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user''fred', 'active': false });
// => 1
 
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0
 
// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2

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

source npm package

此方法类似于 _.findIndex,不同之处在于它从右到左迭代 collection 的元素。

2.0.0

参数

  1. array (Array): 要检查的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。
  3. [fromIndex=array.length-1] (number):开始搜索的索引。

返回值

(number): 返回找到元素的索引值,否则返回 -1。

例子

var users = [
  { 'user''barney',  'active': true },
  { 'user''fred',    'active': false },
  { 'user''pebbles', 'active': false }
];
 
_.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
// => 2
 
// The `_.matches` iteratee shorthand.
_.findLastIndex(users, { 'user''barney', 'active': true });
// => 0
 
// The `_.matchesProperty` iteratee shorthand.
_.findLastIndex(users, ['active', false]);
// => 2
 
// The `_.property` iteratee shorthand.
_.findLastIndex(users, 'active');
// => 0

_.flatten(array)

source npm package

array 扁平化为单层深度。

0.1.0

参数

  1. array (Array):要扁平化的数组。

返回值

(Array):返回新的扁平化数组。

例子

_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]

_.flattenDeep(array)

source npm package

递归地扁平化 array

3.0.0

参数

  1. array (Array):要扁平化的数组。

返回值

(Array):返回新的扁平化数组。

例子

_.flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]

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

source npm package

递归地扁平化 array 最多 depth 次。

4.4.0

参数

  1. array (Array):要扁平化的数组。
  2. [depth=1] (number):最大递归深度。

返回值

(Array):返回新的扁平化数组。

例子

var array = [1, [2, [3, [4]], 5]];
 
_.flattenDepth(array, 1);
// => [1, 2, [3, [4]], 5]
 
_.flattenDepth(array, 2);
// => [1, 2, 3, [4], 5]

_.fromPairs(pairs)

source npm package

_.toPairs 的逆运算;此方法返回由键值对 pairs 组成的对象。

4.0.0

参数

  1. pairs (Array):键值对。

返回值

(Object):返回新对象。

例子

_.fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }

source npm package

获取 array 的第一个元素。

0.1.0

别名

_.first

参数

  1. array (Array): 要查询的数组。

返回值

(*):返回 array 的第一个元素。

例子

_.head([1, 2, 3]);
// => 1
 
_.head([]);
// => undefined

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

source npm package

使用 SameValueZero 进行相等性比较,获取 valuearray 中第一次出现的索引。如果 fromIndex 为负数,则将其用作从 array 末尾开始的偏移量。

0.1.0

参数

  1. array (Array): 要检查的数组。
  2. value (*):要搜索的值。
  3. [fromIndex=0] (number): 开始搜索的索引值。

返回值

(number):返回匹配值的索引,否则返回 -1

例子

_.indexOf([1, 2, 1, 2], 2);
// => 1
 
// Search from the `fromIndex`.
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3

_.initial(array)

source npm package

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

0.1.0

参数

  1. array (Array): 要查询的数组。

返回值

(Array): 返回 array 的切片。

例子

_.initial([1, 2, 3]);
// => [1, 2]

_.intersection([arrays])

source npm package

使用 SameValueZero 进行相等性比较,创建一个包含所有给定数组中都存在的唯一值的数组。结果值的顺序和引用由第一个数组确定。

0.1.0

参数

  1. [arrays] (...Array):要检查的数组。

返回值

(Array):返回包含相交值的新数组。

例子

_.intersection([2, 1], [2, 3]);
// => [2]

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

source npm package

此方法类似于 _.intersection,不同之处在于它接受 iteratee,该参数为每个 arrays 的每个元素调用,以生成比较它们的条件。结果值的顺序和引用由第一个数组确定。迭代器使用一个参数调用
(value).

4.0.0

参数

  1. [arrays] (...Array):要检查的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(Array):返回包含相交值的新数组。

例子

_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [2.1]
 
// The `_.property` iteratee shorthand.
_.intersectionBy([{ 'x'1 }], [{ 'x'2 }, { 'x'1 }], 'x');
// => [{ 'x': 1 }]

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

source npm package

此方法类似于 _.intersection,不同之处在于它接受 comparator,该参数用于比较 arrays 的元素。结果值的顺序和引用由第一个数组确定。比较器使用两个参数调用:(arrVal, othVal)

4.0.0

参数

  1. [arrays] (...Array):要检查的数组。
  2. [comparator] (Function): 每个元素调用的比较函数。

返回值

(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);
// => [{ 'x': 1, 'y': 2 }]

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

source npm package

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

4.0.0

参数

  1. array (Array):要转换的数组。
  2. [separator=','] (string):元素分隔符。

返回值

(string):返回连接后的字符串。

例子

_.join(['a', 'b', 'c'], '~');
// => 'a~b~c'

_.last(array)

source npm package

获取 array 的最后一个元素。

0.1.0

参数

  1. array (Array): 要查询的数组。

返回值

(*):返回 array 的最后一个元素。

例子

_.last([1, 2, 3]);
// => 3

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

source npm package

此方法类似于 _.indexOf,不同之处在于它从右到左迭代 array 的元素。

0.1.0

参数

  1. array (Array): 要检查的数组。
  2. value (*):要搜索的值。
  3. [fromIndex=array.length-1] (number):开始搜索的索引。

返回值

(number):返回匹配值的索引,否则返回 -1

例子

_.lastIndexOf([1, 2, 1, 2], 2);
// => 3
 
// Search from the `fromIndex`.
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 1

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

source npm package

获取 array 中索引为 n 的元素。如果 n 为负数,则返回从末尾开始的第 n 个元素。

4.11.0

参数

  1. array (Array): 要查询的数组。
  2. [n=0] (number):要返回的元素的索引。

返回值

(*):返回 array 的第 n 个元素。

例子

var array = ['a', 'b', 'c', 'd'];
 
_.nth(array, 1);
// => 'b'
 
_.nth(array, -2);
// => 'c';

_.pull(array, [values])

source npm package

使用 SameValueZero 进行相等性比较,从 array 中删除所有给定的值。

注意:_.without 不同,此方法会改变 array。使用 _.remove 按谓词从数组中删除元素。

2.0.0

参数

  1. array (Array):要修改的数组。
  2. [values] (...*):要删除的值。

返回值

(Array): 返回 array。

例子

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
 
_.pull(array, 'a', 'c');
console.log(array);
// => ['b', 'b']

_.pullAll(array, values)

source npm package

此方法类似于 _.pull,不同之处在于它接受要删除的值数组。

注意:_.difference 不同,此方法会改变 array

4.0.0

参数

  1. array (Array):要修改的数组。
  2. values (Array):要删除的值。

返回值

(Array): 返回 array。

例子

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
 
_.pullAll(array, ['a', 'c']);
console.log(array);
// => ['b', 'b']

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

source npm package

此方法类似于 _.pullAll,不同之处在于它接受 iteratee,该参数为 arrayvalues 的每个元素调用,以生成比较它们的条件。迭代器使用一个参数调用:(value)

注意:_.differenceBy 不同,此方法会改变 array

4.0.0

参数

  1. array (Array):要修改的数组。
  2. values (Array):要删除的值。
  3. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(Array): 返回 array。

例子

var array = [{ 'x'1 }, { 'x'2 }, { 'x'3 }, { 'x'1 }];
 
_.pullAllBy(array, [{ 'x'1 }, { 'x'3 }], 'x');
console.log(array);
// => [{ 'x': 2 }]

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

source npm package

此方法类似于 _.pullAll,不同之处在于它接受 comparator,该参数用于比较 arrayvalues 的元素。比较器使用两个参数调用:(arrVal, othVal)

注意:_.differenceWith 不同,此方法会改变 array

4.6.0

参数

  1. array (Array):要修改的数组。
  2. values (Array):要删除的值。
  3. [comparator] (Function): 每个元素调用的比较函数。

返回值

(Array): 返回 array。

例子

var array = [{ 'x'1, 'y'2 }, { 'x'3, 'y'4 }, { 'x'5, 'y'6 }];
 
_.pullAllWith(array, [{ 'x'3, 'y'4 }], _.isEqual);
console.log(array);
// => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]

_.pullAt(array, [indexes])

source npm package

array 中删除与 indexes 对应的元素,并返回包含已删除元素的数组。

注意:_.at 不同,此方法会改变 array

3.0.0

参数

  1. array (Array):要修改的数组。
  2. [indexes] (...(number|number[])):要删除的元素的索引。

返回值

(Array):返回包含已删除元素的新数组。

例子

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

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

source npm package

array 中删除 predicate 返回真值的所有元素,并返回包含已删除元素的数组。谓词使用三个参数调用:(value, index, array)

注意:_.filter 不同,此方法会改变 array。使用 _.pull 按值从数组中拉取元素。

2.0.0

参数

  1. array (Array):要修改的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(Array):返回包含已删除元素的新数组。

例子

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

_.reverse(array)

source npm package

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

注意: 此方法会改变 array,并且基于 Array#reverse

4.0.0

参数

  1. array (Array):要修改的数组。

返回值

(Array): 返回 array。

例子

var array = [1, 2, 3];
 
_.reverse(array);
// => [3, 2, 1]
 
console.log(array);
// => [3, 2, 1]

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

source npm package

创建 array 的切片,从 start 开始,到 end 结束(不包括 end)。

注意: 使用此方法代替 Array#slice 以确保返回密集数组。

3.0.0

参数

  1. array (Array):要切片的数组。
  2. [start=0] (number): 开始位置(默认 0)。
  3. [end=array.length] (number): 结束位置(默认 array.length)。

返回值

(Array): 返回 array 的切片。

_.sortedIndex(array, value)

source npm package

使用二分搜索确定应在 array 中插入 value 的最低索引,以保持其排序顺序。

0.1.0

参数

  1. array (Array):要检查的已排序数组。
  2. value (*):要评估的值。

返回值

(number):返回应在 array 中插入 value 的索引。

例子

_.sortedIndex([30, 50], 40);
// => 1

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

source npm package

此方法类似于 _.sortedIndex,不同之处在于它接受 iteratee,该参数为 valuearray 的每个元素调用,以计算它们的排序等级。迭代器使用一个参数调用:(value)

4.0.0

参数

  1. array (Array):要检查的已排序数组。
  2. value (*):要评估的值。
  3. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(number):返回应在 array 中插入 value 的索引。

例子

var objects = [{ 'x'4 }, { 'x'5 }];
 
_.sortedIndexBy(objects, { 'x'4 }, function(o) { return o.x; });
// => 0
 
// The `_.property` iteratee shorthand.
_.sortedIndexBy(objects, { 'x'4 }, 'x');
// => 0

_.sortedIndexOf(array, value)

source npm package

此方法类似于 _.indexOf,不同之处在于它对已排序的 array 执行二分搜索。

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. value (*):要搜索的值。

返回值

(number):返回匹配值的索引,否则返回 -1

例子

_.sortedIndexOf([4, 5, 5, 5, 6], 5);
// => 1

_.sortedLastIndex(array, value)

source npm package

此方法类似于 _.sortedIndex,不同之处在于它返回应在 array 中插入 value 的最高索引,以保持其排序顺序。

3.0.0

参数

  1. array (Array):要检查的已排序数组。
  2. value (*):要评估的值。

返回值

(number):返回应在 array 中插入 value 的索引。

例子

_.sortedLastIndex([4, 5, 5, 5, 6], 5);
// => 4

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

source npm package

此方法类似于 _.sortedLastIndex,不同之处在于它接受 iteratee,该参数为 valuearray 的每个元素调用,以计算它们的排序等级。迭代器使用一个参数调用:(value)

4.0.0

参数

  1. array (Array):要检查的已排序数组。
  2. value (*):要评估的值。
  3. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(number):返回应在 array 中插入 value 的索引。

例子

var objects = [{ 'x'4 }, { 'x'5 }];
 
_.sortedLastIndexBy(objects, { 'x'4 }, function(o) { return o.x; });
// => 1
 
// The `_.property` iteratee shorthand.
_.sortedLastIndexBy(objects, { 'x'4 }, 'x');
// => 1

_.sortedLastIndexOf(array, value)

source npm package

此方法类似于 _.lastIndexOf,不同之处在于它对已排序的 array 执行二分搜索。

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. value (*):要搜索的值。

返回值

(number):返回匹配值的索引,否则返回 -1

例子

_.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
// => 3

_.sortedUniq(array)

source npm package

此方法类似于 _.uniq,不同之处在于它专为已排序数组设计和优化。

4.0.0

参数

  1. array (Array): 要检查的数组。

返回值

(Array):返回新的无重复项数组。

例子

_.sortedUniq([1, 1, 2]);
// => [1, 2]

_.sortedUniqBy(array, [iteratee])

source npm package

此方法类似于 _.uniqBy,不同之处在于它专为已排序的数组设计和优化。

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. [iteratee] (函数): 每次迭代调用的函数。

返回值

(Array):返回新的无重复项数组。

例子

_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
// => [1.1, 2.3]

_.tail(array)

源代码 npm 包

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

4.0.0

参数

  1. array (Array): 要查询的数组。

返回值

(Array): 返回 array 的切片。

例子

_.tail([1, 2, 3]);
// => [2, 3]

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

源代码 npm 包

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

0.1.0

参数

  1. array (Array): 要查询的数组。
  2. [n=1] (数字): 要提取的元素数量。

返回值

(Array): 返回 array 的切片。

例子

_.take([1, 2, 3]);
// => [1]
 
_.take([1, 2, 3], 2);
// => [1, 2]
 
_.take([1, 2, 3], 5);
// => [1, 2, 3]
 
_.take([1, 2, 3], 0);
// => []

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

源代码 npm 包

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

3.0.0

参数

  1. array (Array): 要查询的数组。
  2. [n=1] (数字): 要提取的元素数量。

返回值

(Array): 返回 array 的切片。

例子

_.takeRight([1, 2, 3]);
// => [3]
 
_.takeRight([1, 2, 3], 2);
// => [2, 3]
 
_.takeRight([1, 2, 3], 5);
// => [1, 2, 3]
 
_.takeRight([1, 2, 3], 0);
// => []

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

源代码 npm 包

创建一个 array 的切片,从末尾提取元素。提取元素直到 predicate 返回假值。该断言函数调用时将传入三个参数:(value, index, array)

3.0.0

参数

  1. array (Array): 要查询的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(Array): 返回 array 的切片。

例子

var users = [
  { 'user''barney',  'active': true },
  { 'user''fred',    'active': false },
  { 'user''pebbles', 'active': false }
];
 
_.takeRightWhile(users, function(o) { return !o.active; });
// => objects for ['fred', 'pebbles']
 
// The `_.matches` iteratee shorthand.
_.takeRightWhile(users, { 'user''pebbles', 'active': false });
// => objects for ['pebbles']
 
// The `_.matchesProperty` iteratee shorthand.
_.takeRightWhile(users, ['active', false]);
// => objects for ['fred', 'pebbles']
 
// The `_.property` iteratee shorthand.
_.takeRightWhile(users, 'active');
// => []

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

源代码 npm 包

创建一个 array 的切片,从开头提取元素。提取元素直到 predicate 返回假值。该断言函数调用时将传入三个参数:(value, index, array)

3.0.0

参数

  1. array (Array): 要查询的数组。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(Array): 返回 array 的切片。

例子

var users = [
  { 'user''barney',  'active': false },
  { 'user''fred',    'active': false },
  { 'user''pebbles', 'active': true }
];
 
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
 
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user''barney', 'active': false });
// => objects for ['barney']
 
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
 
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []

_.union([arrays])

源代码 npm 包

创建一个按顺序排列的唯一值数组,使用 SameValueZero 进行相等性比较,从所有给定数组中获取唯一值。

0.1.0

参数

  1. [arrays] (...Array):要检查的数组。

返回值

(数组): 返回组合值的新的数组。

例子

_.union([2], [1, 2]);
// => [2, 1]

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

源代码 npm 包

此方法类似于 _.union,不同之处在于它接受 iteratee 参数,该参数针对每个 arrays 的每个元素调用,以生成计算唯一性的标准。结果值从出现该值的第一个数组中选择。迭代函数调用时将传入一个参数。
(value).

4.0.0

参数

  1. [arrays] (...Array):要检查的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(数组): 返回组合值的新的数组。

例子

_.unionBy([2.1], [1.2, 2.3], Math.floor);
// => [2.1, 1.2]
 
// The `_.property` iteratee shorthand.
_.unionBy([{ 'x'1 }], [{ 'x'2 }, { 'x'1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]

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

源代码 npm 包

此方法类似于 _.union,不同之处在于它接受 comparator 参数,该参数用于比较 arrays 的元素。结果值从出现该值的第一个数组中选择。比较函数调用时将传入两个参数:(arrVal, othVal)

4.0.0

参数

  1. [arrays] (...Array):要检查的数组。
  2. [comparator] (Function): 每个元素调用的比较函数。

返回值

(数组): 返回组合值的新的数组。

例子

var objects = [{ 'x'1, 'y'2 }, { 'x'2, 'y'1 }];
var others = [{ 'x'1, 'y'1 }, { 'x'1, 'y'2 }];
 
_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

_.uniq(array)

源代码 npm 包

创建一个数组的无重复版本,使用 SameValueZero 进行相等性比较,其中只保留每个元素的第一次出现。结果值的顺序由它们在数组中出现的顺序决定。

0.1.0

参数

  1. array (Array): 要检查的数组。

返回值

(Array):返回新的无重复项数组。

例子

_.uniq([2, 1, 2]);
// => [2, 1]

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

源代码 npm 包

此方法类似于 _.uniq,不同之处在于它接受 iteratee 参数,该参数针对 array 中的每个元素调用,以生成计算唯一性的标准。结果值的顺序由它们在数组中出现的顺序决定。迭代函数调用时将传入一个参数。
(value).

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(Array):返回新的无重复项数组。

例子

_.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]
 
// The `_.property` iteratee shorthand.
_.uniqBy([{ 'x'1 }, { 'x'2 }, { 'x'1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]

_.uniqWith(array, [comparator])

源代码 npm 包

此方法类似于 _.uniq,不同之处在于它接受 comparator 参数,该参数用于比较 array 的元素。结果值的顺序由它们在数组中出现的顺序决定。比较函数调用时将传入两个参数:(arrVal, othVal)

4.0.0

参数

  1. array (Array): 要检查的数组。
  2. [comparator] (Function): 每个元素调用的比较函数。

返回值

(Array):返回新的无重复项数组。

例子

var objects = [{ 'x'1, 'y'2 }, { 'x'2, 'y'1 }, { 'x'1, 'y'2 }];
 
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

_.unzip(array)

源代码 npm 包

此方法类似于 _.zip,不同之处在于它接受一个分组元素的数组,并创建一个数组,将元素重新分组到它们的预压缩配置。

1.2.0

参数

  1. array (数组): 要处理的分组元素的数组。

返回值

(数组): 返回重新分组元素的新数组。

例子

var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
// => [['a', 1, true], ['b', 2, false]]
 
_.unzip(zipped);
// => [['a', 'b'], [1, 2], [true, false]]

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

源代码 npm 包

此方法类似于 _.unzip,不同之处在于它接受 iteratee 参数来指定如何组合重新分组的值。迭代函数调用时将传入每个组的元素:(...group)

3.8.0

参数

  1. array (数组): 要处理的分组元素的数组。
  2. [iteratee=_.identity] (函数): 用于组合重新分组值的函数。

返回值

(数组): 返回重新分组元素的新数组。

例子

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

_.without(array, [values])

源代码 npm 包

创建一个不包含所有给定值的数组,使用 SameValueZero 进行相等性比较。

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

0.1.0

参数

  1. array (Array): 要检查的数组。
  2. [values] (...*): 要排除的值。

返回值

(Array): 返回过滤掉假值后的新数组

例子

_.without([2, 1, 2, 3], 1, 2);
// => [3]

_.xor([arrays])

源代码 npm 包

创建一个唯一值数组,该数组是给定数组的 对称差集。结果值的顺序由它们在数组中出现的顺序决定。

2.4.0

参数

  1. [arrays] (...Array):要检查的数组。

返回值

(Array): 返回过滤掉假值后的新数组

例子

_.xor([2, 1], [2, 3]);
// => [1, 3]

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

源代码 npm 包

此方法类似于 _.xor,不同之处在于它接受 iteratee 参数,该参数针对每个 arrays 的每个元素调用,以生成比较它们的标准。结果值的顺序由它们在数组中出现的顺序决定。迭代函数调用时将传入一个参数:(value)

4.0.0

参数

  1. [arrays] (...Array):要检查的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(Array): 返回过滤掉假值后的新数组

例子

_.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [1.2, 3.4]
 
// The `_.property` iteratee shorthand.
_.xorBy([{ 'x'1 }], [{ 'x'2 }, { 'x'1 }], 'x');
// => [{ 'x': 2 }]

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

源代码 npm 包

此方法类似于 _.xor,不同之处在于它接受 comparator 参数,该参数用于比较 arrays 的元素。结果值的顺序由它们在数组中出现的顺序决定。比较函数调用时将传入两个参数:(arrVal, othVal)

4.0.0

参数

  1. [arrays] (...Array):要检查的数组。
  2. [comparator] (Function): 每个元素调用的比较函数。

返回值

(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);
// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

_.zip([arrays])

源代码 npm 包

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

0.1.0

参数

  1. [arrays] (...数组): 要处理的数组。

返回值

(数组): 返回分组元素的新数组。

例子

_.zip(['a', 'b'], [1, 2], [true, false]);
// => [['a', 1, true], ['b', 2, false]]

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

源代码 npm 包

此方法类似于 _.fromPairs,不同之处在于它接受两个数组,一个属性标识符数组和一个相应值数组。

0.4.0

参数

  1. [props=[]] (数组): 属性标识符。
  2. [values=[]] (数组): 属性值。

返回值

(Object):返回新对象。

例子

_.zipObject(['a', 'b'], [1, 2]);
// => { 'a': 1, 'b': 2 }

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

源代码 npm 包

此方法类似于 _.zipObject,不同之处在于它支持属性路径。

4.1.0

参数

  1. [props=[]] (数组): 属性标识符。
  2. [values=[]] (数组): 属性值。

返回值

(Object):返回新对象。

例子

_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }

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

源代码 npm 包

此方法类似于 _.zip,不同之处在于它接受 iteratee 参数来指定如何组合分组的值。迭代函数调用时将传入每个组的元素:(...group)

3.8.0

参数

  1. [arrays] (...数组): 要处理的数组。
  2. [iteratee=_.identity] (函数): 用于组合分组值的函数。

返回值

(数组): 返回分组元素的新数组。

例子

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

“集合” 方法

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

源代码 npm 包

创建一个对象,其键是通过对 collection 中的每个元素运行 iteratee 函数的结果生成的。每个键对应的值是 iteratee 函数返回该键的次数。迭代函数调用时将传入一个参数:(value)

0.5.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 用于转换键的迭代函数。

返回值

(对象): 返回组合的聚合对象。

例子

_.countBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': 1, '6': 2 }
 
// The `_.property` iteratee shorthand.
_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }

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

源代码 npm 包

检查 predicate 是否对 collection所有元素都返回真值。一旦 predicate 返回假值,迭代就会停止。断言函数调用时将传入三个参数:(value, index|key, collection)

注意: 对于 空集合,此方法返回 true,因为 空集合的元素都为真

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(布尔值): 如果所有元素都通过断言函数检查,则返回 true,否则返回 false

例子

_.every([true, 1, null, 'yes'], Boolean);
// => false
 
var users = [
  { 'user''barney', 'age'36, 'active': false },
  { 'user''fred',   'age'40, 'active': false }
];
 
// The `_.matches` iteratee shorthand.
_.every(users, { 'user''barney', 'active': false });
// => false
 
// The `_.matchesProperty` iteratee shorthand.
_.every(users, ['active', false]);
// => true
 
// The `_.property` iteratee shorthand.
_.every(users, 'active');
// => false

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

源代码 npm 包

迭代 collection 的元素,返回一个包含 predicate 返回真值的所有元素的数组。断言函数调用时将传入三个参数:(value, index|key, collection)

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

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(数组): 返回新的过滤后的数组。

例子

var users = [
  { 'user''barney', 'age'36, 'active': true },
  { 'user''fred',   'age'40, 'active': false }
];
 
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
 
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age'36, 'active': true });
// => objects for ['barney']
 
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
 
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']

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

源代码 npm 包

迭代 collection 的元素,返回 predicate 返回真值的第一个元素。断言函数调用时将传入三个参数:(value, index|key, collection)

0.1.0

参数

  1. collection (数组|对象): 要检查的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。
  3. [fromIndex=0] (number): 开始搜索的索引值。

返回值

(*): 返回匹配的元素,否则返回 undefined

例子

var users = [
  { 'user''barney',  'age'36, 'active': true },
  { 'user''fred',    'age'40, 'active': false },
  { 'user''pebbles', 'age'1,  'active': true }
];
 
_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'
 
// The `_.matches` iteratee shorthand.
_.find(users, { 'age'1, 'active': true });
// => object for 'pebbles'
 
// The `_.matchesProperty` iteratee shorthand.
_.find(users, ['active', false]);
// => object for 'fred'
 
// The `_.property` iteratee shorthand.
_.find(users, 'active');
// => object for 'barney'

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

源代码 npm 包

此方法类似于 _.find,不同之处在于它从右到左迭代 collection 的元素。

2.0.0

参数

  1. collection (数组|对象): 要检查的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。
  3. [fromIndex=collection.length-1] (数字): 开始搜索的索引。

返回值

(*): 返回匹配的元素,否则返回 undefined

例子

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

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

源代码 npm 包

通过对 collection 中的每个元素运行 iteratee 函数并展平映射的结果,创建一个展平的值数组。迭代函数调用时将传入三个参数:(value, index|key, collection)

4.0.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(Array):返回新的扁平化数组。

例子

function duplicate(n) {
  return [n, n];
}
 
_.flatMap([1, 2], duplicate);
// => [1, 1, 2, 2]

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

源代码 npm 包

此方法类似于 _.flatMap,不同之处在于它递归地展平映射的结果。

4.7.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(Array):返回新的扁平化数组。

例子

function duplicate(n) {
  return [[[n, n]]];
}
 
_.flatMapDeep([1, 2], duplicate);
// => [1, 1, 2, 2]

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

源代码 npm 包

此方法类似于 _.flatMap,不同之处在于它会递归地将映射结果展平最多 depth 次。

4.7.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。
  3. [depth=1] (number):最大递归深度。

返回值

(Array):返回新的扁平化数组。

例子

function duplicate(n) {
  return [[[n, n]]];
}
 
_.flatMapDepth([1, 2], duplicate, 2);
// => [[1, 1], [2, 2]]

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

源代码 npm 包

遍历 collection 的元素并为每个元素调用 iteratee。使用三个参数调用迭代函数:(value, index|key, collection)。迭代函数可以通过显式返回 false 来提前退出迭代。

注意:与其他“集合”方法一样,具有“length”属性的对象将像数组一样进行迭代。为避免此行为,请使用 _.forIn_.forOwn 进行对象迭代。

0.1.0

别名

_.each

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(*):返回 collection

例子

_.forEach([1, 2], function(value) {
  console.log(value);
});
// => Logs `1` then `2`.
 
_.forEach({ 'a'1, 'b'2 }, function(value, key) {
  console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).

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

源代码 npm 包

此方法类似于 _.forEach,不同之处在于它从右到左遍历 collection 的元素。

2.0.0

别名

_.eachRight

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(*):返回 collection

例子

_.forEachRight([1, 2], function(value) {
  console.log(value);
});
// => Logs `2` then `1`.

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

源代码 npm 包

创建一个对象,其键是由 collection 的每个元素通过 iteratee 运行的结果生成的。分组值的顺序由它们在 collection 中出现的顺序决定。每个键的对应值是一个负责生成该键的元素数组。使用一个参数调用迭代函数:(value)

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 用于转换键的迭代函数。

返回值

(对象): 返回组合的聚合对象。

例子

_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }
 
// The `_.property` iteratee shorthand.
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }

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

源代码 npm 包

检查 value 是否在 collection 中。如果 collection 是字符串,则检查它是否是 value 的子字符串,否则使用 SameValueZero 进行相等比较。如果 fromIndex 为负数,则将其用作从 collection 末尾开始的偏移量。

0.1.0

参数

  1. collection (Array|Object|string):要检查的集合。
  2. value (*):要搜索的值。
  3. [fromIndex=0] (number): 开始搜索的索引值。

返回值

(boolean):如果找到 value,则返回 true,否则返回 false

例子

_.includes([1, 2, 3], 1);
// => true
 
_.includes([1, 2, 3], 1, 2);
// => false
 
_.includes({ 'a'1, 'b'2 }, 1);
// => true
 
_.includes('abcd', 'bc');
// => true

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

源代码 npm 包

调用 collection 中每个元素的 path 处的方法,返回一个包含每个已调用方法的结果的数组。所有其他参数都将提供给每个已调用的方法。如果 path 是函数,则将为 collection 中的每个元素调用它,并将 this 绑定到该元素。

4.0.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. path (Array|Function|string):要调用的方法的路径或每次迭代调用的函数。
  3. [args] (...*):用于调用每个方法的参数。

返回值

(Array):返回结果数组。

例子

_.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]]
 
_.invokeMap([123, 456], String.prototype.split, '');
// => [['1', '2', '3'], ['4', '5', '6']]

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

源代码 npm 包

创建一个对象,其键是由 collection 的每个元素通过 iteratee 运行的结果生成的。每个键的对应值是负责生成该键的最后一个元素。使用一个参数调用迭代函数:(value)

4.0.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 用于转换键的迭代函数。

返回值

(对象): 返回组合的聚合对象。

例子

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

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

源代码 npm 包

通过运行 collection 中的每个元素来创建一个值数组 iteratee。使用三个参数调用迭代函数
(value, index|key, collection).

许多 lodash 方法都被保护为迭代函数,用于诸如 _.every_.filter_.map_.mapValues_.reject_.some 之类的方法。

受保护的方法有
arychunkcurrycurryRightdropdropRighteveryfillinvertparseIntrandomrangerangeRightrepeatsampleSizeslicesomesortBysplittaketakeRighttemplatetrimtrimEndtrimStartwords

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(Array):返回新的映射数组。

例子

function square(n) {
  return n * n;
}
 
_.map([4, 8], square);
// => [16, 64]
 
_.map({ 'a'4, 'b'8 }, square);
// => [16, 64] (iteration order is not guaranteed)
 
var users = [
  { 'user''barney' },
  { 'user''fred' }
];
 
// The `_.property` iteratee shorthand.
_.map(users, 'user');
// => ['barney', 'fred']

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

源代码 npm 包

此方法类似于 _.sortBy,不同之处在于它允许指定要排序的迭代函数的排序顺序。如果未指定 orders,则所有值都按升序排序。否则,为相应值的降序或升序排序顺序指定“desc”或“asc”顺序。

4.0.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]):要排序的迭代函数。
  3. [orders] (string[])iteratees 的排序顺序。

返回值

(Array):返回新的排序数组。

例子

var users = [
  { 'user''fred',   'age'48 },
  { 'user''barney', 'age'34 },
  { 'user''fred',   'age'40 },
  { 'user''barney', 'age'36 }
];
 
// Sort by `user` in ascending order and by `age` in descending order.
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]

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

源代码 npm 包

创建一个元素数组,该数组分为两组,第一组包含 predicate 返回真值的元素,第二组包含 predicate 返回假值的元素。使用一个参数调用谓词函数:(value)

3.0.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(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; });
// => objects for [['fred'], ['barney', 'pebbles']]
 
// The `_.matches` iteratee shorthand.
_.partition(users, { 'age'1, 'active': false });
// => objects for [['pebbles'], ['barney', 'fred']]
 
// The `_.matchesProperty` iteratee shorthand.
_.partition(users, ['active', false]);
// => objects for [['barney', 'pebbles'], ['fred']]
 
// The `_.property` iteratee shorthand.
_.partition(users, 'active');
// => objects for [['fred'], ['barney', 'pebbles']]

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

源代码 npm 包

collection 简化为一个值,该值是通过 iteratee 运行 collection 中的每个元素的累积结果,其中每次连续调用都提供前一次调用的返回值。如果未提供 accumulator,则使用 collection 的第一个元素作为初始值。使用四个参数调用迭代函数
(accumulator, value, index|key, collection).

许多 lodash 方法都被保护为迭代函数,用于诸如 _.reduce_.reduceRight_.transform 之类的方法。

受保护的方法有
assigndefaultsdefaultsDeepincludesmergeorderBysortBy

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。
  3. [accumulator] (*):初始值。

返回值

(*):返回累积值。

例子

_.reduce([1, 2], function(sum, n) {
  return sum + n;
}, 0);
// => 3
 
_.reduce({ 'a'1, 'b'2, 'c'1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
  return result;
}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)

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

源代码 npm 包

此方法类似于 _.reduce,不同之处在于它从右到左遍历 collection 的元素。

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。
  3. [accumulator] (*):初始值。

返回值

(*):返回累积值。

例子

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

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

源代码 npm 包

_.filter 相反;此方法返回 collectionpredicate 返回真值的元素。

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(数组): 返回新的过滤后的数组。

例子

var users = [
  { 'user''barney', 'age'36, 'active': false },
  { 'user''fred',   'age'40, 'active': true }
];
 
_.reject(users, function(o) { return !o.active; });
// => objects for ['fred']
 
// The `_.matches` iteratee shorthand.
_.reject(users, { 'age'40, 'active': true });
// => objects for ['barney']
 
// The `_.matchesProperty` iteratee shorthand.
_.reject(users, ['active', false]);
// => objects for ['fred']
 
// The `_.property` iteratee shorthand.
_.reject(users, 'active');
// => objects for ['barney']

_.sample(collection)

源代码 npm 包

collection 中获取一个随机元素。

2.0.0

参数

  1. collection (Array|Object):要从中采样的集合。

返回值

(*):返回随机元素。

例子

_.sample([1, 2, 3, 4]);
// => 2

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

源代码 npm 包

collection 中获取 n 个唯一键处的随机元素,最多获取 collection 的大小。

4.0.0

参数

  1. collection (Array|Object):要从中采样的集合。
  2. [n=1] (number):要采样的元素数量。

返回值

(Array):返回随机元素。

例子

_.sampleSize([1, 2, 3], 2);
// => [3, 1]
 
_.sampleSize([1, 2, 3], 4);
// => [2, 3, 1]

_.shuffle(collection)

源代码 npm 包

使用 Fisher-Yates 洗牌算法 的版本创建一个打乱值的数组。

0.1.0

参数

  1. collection (Array|Object):要打乱的集合。

返回值

(Array):返回新的打乱数组。

例子

_.shuffle([1, 2, 3, 4]);
// => [4, 1, 3, 2]

_.size(collection)

源代码 npm 包

通过返回类数组值的长度或对象自身可枚举字符串键属性的数量来获取 collection 的大小。

0.1.0

参数

  1. collection (Array|Object|string):要检查的集合。

返回值

(number):返回集合大小。

例子

_.size([1, 2, 3]);
// => 3
 
_.size({ 'a'1, 'b'2 });
// => 2
 
_.size('pebbles');
// => 7

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

源代码 npm 包

检查 predicate 是否对 collection任何元素返回真值。一旦 predicate 返回真值,迭代就会停止。使用三个参数调用谓词函数:(value, index|key, collection)

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(boolean):如果任何元素通过谓词检查,则返回 true,否则返回 false

例子

_.some([null, 0, 'yes', false], Boolean);
// => true
 
var users = [
  { 'user''barney', 'active': true },
  { 'user''fred',   'active': false }
];
 
// The `_.matches` iteratee shorthand.
_.some(users, { 'user''barney', 'active': false });
// => false
 
// The `_.matchesProperty` iteratee shorthand.
_.some(users, ['active', false]);
// => true
 
// The `_.property` iteratee shorthand.
_.some(users, 'active');
// => true

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

源代码 npm 包

创建一个元素数组,该数组按在集合中运行每个元素通过每个迭代函数的结果按升序排序。此方法执行稳定排序,也就是说,它保留相等元素的原始排序顺序。使用一个参数调用迭代函数:(value)

0.1.0

参数

  1. collection (数组|对象): 要迭代的集合。
  2. [iteratees=[_.identity]] (...(Function|Function[])):要排序的迭代函数。

返回值

(Array):返回新的排序数组。

例子

var users = [
  { 'user''fred',   'age'48 },
  { 'user''barney', 'age'36 },
  { 'user''fred',   'age'40 },
  { 'user''barney', 'age'34 }
];
 
_.sortBy(users, [function(o) { return o.user; }]);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
 
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]

“日期”方法

_.now()

源代码 npm 包

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

2.4.0

返回值

(number):返回时间戳。

例子

_.defer(function(stamp) {
  console.log(_.now() - stamp);
}, _.now());
// => Logs the number of milliseconds it took for the deferred invocation.

“函数”方法

_.after(n, func)

源代码 npm 包

_.before 相反;此方法创建一个函数,该函数在其被调用 n 次或更多次后调用 func

0.1.0

参数

  1. n (number):在调用 func 之前的调用次数。
  2. func (Function):要限制的函数。

返回值

(Function):返回新的受限函数。

例子

var saves = ['profile', 'settings'];
 
var done = _.after(saves.length, function() {
  console.log('done saving!');
});
 
_.forEach(saves, function(type) {
  asyncSave({ 'type': type, 'complete': done });
});
// => Logs 'done saving!' after the two async saves have completed.

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

源代码 npm 包

创建一个函数,该函数调用 func,最多使用 n 个参数,忽略任何其他参数。

3.0.0

参数

  1. func (Function):要限制参数的函数。
  2. [n=func.length] (number):参数数量上限。

返回值

(Function):返回新的受限函数。

例子

_.map(['6', '8', '10'], _.ary(parseInt, 1));
// => [6, 8, 10]

_.before(n, func)

源代码 npm 包

创建一个函数,该函数使用创建函数的 this 绑定和参数调用 func,而它被调用的次数小于 n 次。对创建函数的后续调用将返回最后一次 func 调用的结果。

3.0.0

参数

  1. n (number):不再调用 func 的调用次数。
  2. func (Function):要限制的函数。

返回值

(Function):返回新的受限函数。

例子

jQuery(element).on('click', _.before(5, addContactToList));
// => Allows adding up to 4 contacts to the list.

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

源代码 npm 包

创建一个函数,该函数使用 thisArgthis 绑定和预置在其接收的参数之前的 partials 调用 func

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

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

0.1.0

参数

  1. func (Function):要绑定的函数。
  2. thisArg (*)functhis 绑定。
  3. [partials] (...*):要部分应用的参数。

返回值

(函数):返回新的绑定函数。

例子

function greet(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
}
 
var object = { 'user''fred' };
 
var bound = _.bind(greet, object, 'hi');
bound('!');
// => 'hi fred!'
 
// Bound with placeholders.
var bound = _.bind(greet, object, _, '!');
bound('hi');
// => 'hi fred!'

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

源代码 npm 包

创建一个函数,该函数使用预先添加到其接收到的参数中的 partials 调用 object[key] 处的方法。

此方法与 _.bind 的不同之处在于,绑定函数可以引用可能重新定义或尚不存在的方法。有关更多详细信息,请参阅 Peter Michaux 的文章

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

0.10.0

参数

  1. object (对象):要调用其方法的对象。
  2. key (字符串):方法的键。
  3. [partials] (...*):要部分应用的参数。

返回值

(函数):返回新的绑定函数。

例子

var object = {
  'user''fred',
  'greet'function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};
 
var bound = _.bindKey(object, 'greet', 'hi');
bound('!');
// => 'hi fred!'
 
object.greet = function(greeting, punctuation) {
  return greeting + 'ya ' + this.user + punctuation;
};
 
bound('!');
// => 'hiya fred!'
 
// Bound with placeholders.
var bound = _.bindKey(object, 'greet', _, '!');
bound('hi');
// => 'hiya fred!'

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

源代码 npm 包

创建一个函数,该函数接受 func 的参数,如果至少提供了 arity 个参数,则调用 func 并返回其结果,否则返回一个接受剩余 func 参数的函数,依此类推。如果 func.length 不够,则可以指定 func 的元数。

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

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

2.0.0

参数

  1. func (函数):要进行柯里化的函数。
  2. [arity=func.length] (数字)func 的元数。

返回值

(函数):返回新的柯里化函数。

例子

var abc = function(a, b, c) {
  return [a, b, c];
};
 
var curried = _.curry(abc);
 
curried(1)(2)(3);
// => [1, 2, 3]
 
curried(1, 2)(3);
// => [1, 2, 3]
 
curried(1, 2, 3);
// => [1, 2, 3]
 
// Curried with placeholders.
curried(1)(_, 3)(2);
// => [1, 3, 2]

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

源代码 npm 包

此方法类似于 _.curry,不同之处在于参数以 _.partialRight 而不是 _.partial 的方式应用于 func

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

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

3.0.0

参数

  1. func (函数):要进行柯里化的函数。
  2. [arity=func.length] (数字)func 的元数。

返回值

(函数):返回新的柯里化函数。

例子

var abc = function(a, b, c) {
  return [a, b, c];
};
 
var curried = _.curryRight(abc);
 
curried(3)(2)(1);
// => [1, 2, 3]
 
curried(2, 3)(1);
// => [1, 2, 3]
 
curried(1, 2, 3);
// => [1, 2, 3]
 
// Curried with placeholders.
curried(3)(1, _)(2);
// => [1, 2, 3]

_.debounce(func, [wait=0], [options={}])

源代码 npm 包

创建一个防抖函数,该函数将延迟调用 func,直到自上次调用防抖函数以来经过了 wait 毫秒。防抖函数带有一个 cancel 方法,用于取消延迟的 func 调用,以及一个 flush 方法,用于立即调用它们。提供 options 以指示是否应在 wait 超时的前沿和/或后沿调用 func。使用提供给防抖函数的最后一个参数调用 func。对防抖函数的后续调用将返回最后一次 func 调用的结果。

**注意:** 如果 leadingtrailing 选项均为 true,则仅当在 wait 超时期间多次调用防抖函数时,才会在超时的后沿调用 func

如果 wait0leadingfalse,则 func 调用将推迟到下一个计时器周期,类似于超时时间为 0setTimeout

有关 _.debounce_.throttle 之间差异的详细信息,请参阅 David Corbacho 的文章

0.1.0

参数

  1. func (函数):要进行防抖的函数。
  2. [wait=0] (数字):延迟的毫秒数。
  3. [options={}] (对象):选项对象。
  4. [options.leading=false] (布尔值):指定在超时的前沿调用。
  5. [options.maxWait] (数字):允许延迟 func 调用之前,允许的最长时间。
  6. [options.trailing=true] (布尔值):指定在超时的后沿调用。

返回值

(函数):返回新的防抖函数。

例子

// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));
 
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = _.debounce(batchLog, 250, { 'maxWait'1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
 
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);

_.defer(func, [args])

源代码 npm 包

推迟调用 func,直到当前调用堆栈已清除。调用 func 时,将向其提供任何其他参数。

0.1.0

参数

  1. func (函数):要推迟的函数。
  2. [args] (...*):用于调用 func 的参数。

返回值

(数字):返回计时器 ID。

例子

_.defer(function(text) {
  console.log(text);
}, 'deferred');
// => Logs 'deferred' after one millisecond.

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

源代码 npm 包

wait 毫秒后调用 func。调用 func 时,将向其提供任何其他参数。

0.1.0

参数

  1. func (函数):要延迟的函数。
  2. wait (数字):延迟调用的毫秒数。
  3. [args] (...*):用于调用 func 的参数。

返回值

(数字):返回计时器 ID。

例子

_.delay(function(text) {
  console.log(text);
}, 1000, 'later');
// => Logs 'later' after one second.

_.flip(func)

源代码 npm 包

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

4.0.0

参数

  1. func (函数):要反转其参数的函数。

返回值

(函数):返回新的反转函数。

例子

var flipped = _.flip(function() {
  return _.toArray(arguments);
});
 
flipped('a', 'b', 'c', 'd');
// => ['d', 'c', 'b', 'a']

_.memoize(func, [resolver])

源代码 npm 包

创建一个记忆 func 结果的函数。如果提供了 resolver,它将根据提供给记忆函数的参数确定用于存储结果的缓存键。默认情况下,提供给记忆函数的第一个参数用作映射缓存键。使用记忆函数的 this 绑定调用 func

**注意:** 缓存作为记忆函数上的 cache 属性公开。可以通过将 _.memoize.Cache 构造函数替换为其实例实现 Map 方法接口(cleardeletegethasset)的构造函数来自定义其创建。

0.1.0

参数

  1. func (函数):要记忆其输出的函数。
  2. [resolver] (函数):用于解析缓存键的函数。

返回值

(函数):返回新的记忆函数。

例子

var object = { 'a'1, 'b'2 };
var other = { 'c'3, 'd'4 };
 
var values = _.memoize(_.values);
values(object);
// => [1, 2]
 
values(other);
// => [3, 4]
 
object.a = 2;
values(object);
// => [1, 2]
 
// Modify the result cache.
values.cache.set(object, ['a', 'b']);
values(object);
// => ['a', 'b']
 
// Replace `_.memoize.Cache`.
_.memoize.Cache = WeakMap;

_.negate(predicate)

源代码 npm 包

创建一个否定谓词 func 结果的函数。使用创建函数的 this 绑定和参数调用 func 谓词。

3.0.0

参数

  1. predicate (函数):要否定的谓词。

返回值

(函数):返回新的否定函数。

例子

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

_.once(func)

源代码 npm 包

创建一个仅限于调用 func 一次的函数。对该函数的重复调用将返回第一次调用的值。使用创建函数的 this 绑定和参数调用 func

0.1.0

参数

  1. func (Function):要限制的函数。

返回值

(Function):返回新的受限函数。

例子

var initialize = _.once(createApplication);
initialize();
initialize();
// => `createApplication` is invoked once

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

源代码 npm 包

创建一个使用其转换后的参数调用 func 的函数。

4.0.0

参数

  1. func (函数):要包装的函数。
  2. [transforms=[_.identity]] (...(Function|Function[])):参数转换。

返回值

(函数):返回新函数。

例子

function doubled(n) {
  return n * 2;
}
 
function square(n) {
  return n * n;
}
 
var func = _.overArgs(function(x, y) {
  return [x, y];
}, [square, doubled]);
 
func(9, 3);
// => [81, 6]
 
func(10, 5);
// => [100, 10]

_.partial(func, [partials])

源代码 npm 包

创建一个函数,该函数使用预先添加到其接收到的参数中的 partials 调用 func。此方法类似于 _.bind,不同之处在于它**不会**更改 this 绑定。

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

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

0.2.0

参数

  1. func (函数):要部分应用参数的函数。
  2. [partials] (...*):要部分应用的参数。

返回值

(函数):返回新的部分应用函数。

例子

function greet(greeting, name) {
  return greeting + ' ' + name;
}
 
var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// => 'hello fred'
 
// Partially applied with placeholders.
var greetFred = _.partial(greet, _, 'fred');
greetFred('hi');
// => 'hi fred'

_.partialRight(func, [partials])

源代码 npm 包

此方法类似于 _.partial,不同之处在于部分应用的参数会附加到其接收到的参数中。

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

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

1.0.0

参数

  1. func (函数):要部分应用参数的函数。
  2. [partials] (...*):要部分应用的参数。

返回值

(函数):返回新的部分应用函数。

例子

function greet(greeting, name) {
  return greeting + ' ' + name;
}
 
var greetFred = _.partialRight(greet, 'fred');
greetFred('hi');
// => 'hi fred'
 
// Partially applied with placeholders.
var sayHelloTo = _.partialRight(greet, 'hello', _);
sayHelloTo('fred');
// => 'hello fred'

_.rearg(func, indexes)

源代码 npm 包

创建一个函数,该函数使用根据指定的 indexes 排列的参数调用 func,其中第一个索引处的参数值作为第一个参数提供,第二个索引处的参数值作为第二个参数提供,依此类推。

3.0.0

参数

  1. func (函数):要重新排列其参数的函数。
  2. indexes (...(number|number[])):排列的参数索引。

返回值

(函数):返回新函数。

例子

var rearged = _.rearg(function(a, b, c) {
  return [a, b, c];
}, [2, 0, 1]);
 
rearged('b', 'c', 'a')
// => ['a', 'b', 'c']

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

源代码 npm 包

创建一个函数,该函数使用创建函数的 this 绑定调用 func,并将 start 及之后的参数作为数组提供。

**注意:** 此方法基于 剩余参数

4.0.0

参数

  1. func (函数):要应用剩余参数的函数。
  2. [start=func.length-1] (数字):剩余参数的起始位置。

返回值

(函数):返回新函数。

例子

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

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

源代码 npm 包

创建一个函数,该函数使用创建函数的 this 绑定和参数数组调用 func,非常类似于 Function#apply

**注意:** 此方法基于 展开运算符

3.2.0

参数

  1. func (函数):要展开参数的函数。
  2. [start=0] (数字):展开的起始位置。

返回值

(函数):返回新函数。

例子

var say = _.spread(function(who, what) {
  return who + ' says ' + what;
});
 
say(['fred', 'hello']);
// => 'fred says hello'
 
var numbers = Promise.all([
  Promise.resolve(40),
  Promise.resolve(36)
]);
 
numbers.then(_.spread(function(x, y) {
  return x + y;
}));
// => a Promise of 76

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

源代码 npm 包

创建一个节流函数,该函数每 wait 毫秒最多调用 func 一次。节流函数带有一个 cancel 方法,用于取消延迟的 func 调用,以及一个 flush 方法,用于立即调用它们。提供 options 以指示是否应在 wait 超时的前沿和/或后沿调用 func。使用提供给节流函数的最后一个参数调用 func。对节流函数的后续调用将返回最后一次 func 调用的结果。

**注意:** 如果 leadingtrailing 选项均为 true,则仅当在 wait 超时期间多次调用节流函数时,才会在超时的后沿调用 func

如果 wait0leadingfalse,则 func 调用将推迟到下一个计时器周期,类似于超时时间为 0setTimeout

有关 _.throttle_.debounce 之间差异的详细信息,请参阅 David Corbacho 的文章

0.1.0

参数

  1. func (函数):要进行节流的函数。
  2. [wait=0] (数字):将调用节流到的毫秒数。
  3. [options={}] (对象):选项对象。
  4. [options.leading=true] (布尔值):指定在超时的前沿调用。
  5. [options.trailing=true] (布尔值):指定在超时的后沿调用。

返回值

(函数):返回新的节流函数。

例子

// Avoid excessively updating the position while scrolling.
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 
// Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
 
// Cancel the trailing throttled invocation.
jQuery(window).on('popstate', throttled.cancel);

_.unary(func)

源代码 npm 包

创建一个最多接受一个参数的函数,忽略任何其他参数。

4.0.0

参数

  1. func (Function):要限制参数的函数。

返回值

(Function):返回新的受限函数。

例子

_.map(['6', '8', '10'], _.unary(parseInt));
// => [6, 8, 10]

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

源代码 npm 包

创建一个函数,将 value 作为第一个参数提供给 wrapper。提供给该函数的任何其他参数都将附加到提供给 wrapper 的参数中。使用创建函数的 this 绑定调用包装器。

0.1.0

参数

  1. value (*): 要包装的值。
  2. [wrapper=identity] (函数): 包装函数。

返回值

(函数):返回新函数。

例子

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

“语言”方法

_.castArray(value)

源代码 npm 包

如果 value 不是数组,则将其转换为数组。

4.4.0

参数

  1. value (*): 要检查的值。

返回值

(数组): 返回转换后的数组。

例子

_.castArray(1);
// => [1]
 
_.castArray({ 'a'1 });
// => [{ 'a': 1 }]
 
_.castArray('abc');
// => ['abc']
 
_.castArray(null);
// => [null]
 
_.castArray(undefined);
// => [undefined]
 
_.castArray();
// => []
 
var array = [1, 2, 3];
console.log(_.castArray(array) === array);
// => true

_.clone(value)

源代码 npm 包

创建 value 的浅拷贝。

注意: 此方法大致基于 结构化克隆算法,支持克隆数组、数组缓冲区、布尔值、日期对象、映射、数字、Object 对象、正则表达式、集合、字符串、符号和类型化数组。arguments 对象的自有可枚举属性将被克隆为普通对象。对于不可克隆的值(例如错误对象、函数、DOM 节点和 WeakMap),将返回一个空对象。

0.1.0

参数

  1. value (*): 要克隆的值。

返回值

(*): 返回克隆的值。

例子

var objects = [{ 'a'1 }, { 'b'2 }];
 
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true

_.cloneDeep(value)

源代码 npm 包

此方法类似于 _.clone,不同之处在于它会递归克隆 value

1.0.0

参数

  1. value (*): 要递归克隆的值。

返回值

(*): 返回深度克隆的值。

例子

var objects = [{ 'a'1 }, { 'b'2 }];
 
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

_.cloneDeepWith(value, [customizer])

源代码 npm 包

此方法类似于 _.cloneWith,不同之处在于它会递归克隆 value

4.0.0

参数

  1. value (*): 要递归克隆的值。
  2. [customizer] (函数): 用于自定义克隆的函数。

返回值

(*): 返回深度克隆的值。

例子

function customizer(value) {
  if (_.isElement(value)) {
    return value.cloneNode(true);
  }
}
 
var el = _.cloneDeepWith(document.body, customizer);
 
console.log(el === document.body);
// => false
console.log(el.nodeName);
// => 'BODY'
console.log(el.childNodes.length);
// => 20

_.cloneWith(value, [customizer])

源代码 npm 包

此方法类似于 _.clone,不同之处在于它接受 customizer,该参数用于生成克隆值。如果 customizer 返回 undefined,则由该方法处理克隆。最多可以使用四个参数调用 customizer;*(value [, index|key, object, stack])*。

4.0.0

参数

  1. value (*): 要克隆的值。
  2. [customizer] (函数): 用于自定义克隆的函数。

返回值

(*): 返回克隆的值。

例子

function customizer(value) {
  if (_.isElement(value)) {
    return value.cloneNode(false);
  }
}
 
var el = _.cloneWith(document.body, customizer);
 
console.log(el === document.body);
// => false
console.log(el.nodeName);
// => 'BODY'
console.log(el.childNodes.length);
// => 0

_.conformsTo(object, source)

源代码 npm 包

通过使用 object 的相应属性值调用 source 的谓词属性,检查 object 是否符合 source

注意:source 被部分应用时,此方法等效于 _.conforms

4.14.0

参数

  1. object (对象): 要检查的对象。
  2. source (对象): 要符合的属性谓词对象。

返回值

(布尔值): 如果 object 符合,则返回 true,否则返回 false

例子

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

_.eq(value, other)

源代码 npm 包

对两个值执行 SameValueZero 比较,以确定它们是否相等。

4.0.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。

返回值

(布尔值): 如果值相等,则返回 true,否则返回 false

例子

var object = { 'a'1 };
var other = { 'a'1 };
 
_.eq(object, object);
// => true
 
_.eq(object, other);
// => false
 
_.eq('a', 'a');
// => true
 
_.eq('a', Object('a'));
// => false
 
_.eq(NaN, NaN);
// => true

_.gt(value, other)

源代码 npm 包

检查 value 是否大于 other

3.9.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。

返回值

(布尔值): 如果 value 大于 other,则返回 true,否则返回 false

例子

_.gt(3, 1);
// => true
 
_.gt(3, 3);
// => false
 
_.gt(1, 3);
// => false

_.gte(value, other)

源代码 npm 包

检查 value 是否大于或等于 other

3.9.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。

返回值

(布尔值): 如果 value 大于或等于 other,则返回 true,否则返回 false

例子

_.gte(3, 1);
// => true
 
_.gte(3, 3);
// => true
 
_.gte(1, 3);
// => false

_.isArguments(value)

源代码 npm 包

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

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 valuearguments 对象,则返回 true,否则返回 false

例子

_.isArguments(function() { return arguments; }());
// => true
 
_.isArguments([1, 2, 3]);
// => false

_.isArray(value)

源代码 npm 包

检查 value 是否被归类为 Array 对象。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是数组,则返回 true,否则返回 false

例子

_.isArray([1, 2, 3]);
// => true
 
_.isArray(document.body.children);
// => false
 
_.isArray('abc');
// => false
 
_.isArray(_.noop);
// => false

_.isArrayBuffer(value)

源代码 npm 包

检查 value 是否被归类为 ArrayBuffer 对象。

4.3.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是数组缓冲区,则返回 true,否则返回 false

例子

_.isArrayBuffer(new ArrayBuffer(2));
// => true
 
_.isArrayBuffer(new Array(2));
// => false

_.isArrayLike(value)

源代码 npm 包

检查 value 是否类似数组。如果值不是函数并且其 value.length 是大于或等于 0 且小于或等于 Number.MAX_SAFE_INTEGER 的整数,则该值被视为类似数组。

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 类似数组,则返回 true,否则返回 false

例子

_.isArrayLike([1, 2, 3]);
// => true
 
_.isArrayLike(document.body.children);
// => true
 
_.isArrayLike('abc');
// => true
 
_.isArrayLike(_.noop);
// => false

_.isArrayLikeObject(value)

源代码 npm 包

此方法类似于 _.isArrayLike,不同之处在于它还会检查 value 是否为对象。

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是类似数组的对象,则返回 true,否则返回 false

例子

_.isArrayLikeObject([1, 2, 3]);
// => true
 
_.isArrayLikeObject(document.body.children);
// => true
 
_.isArrayLikeObject('abc');
// => false
 
_.isArrayLikeObject(_.noop);
// => false

_.isBoolean(value)

源代码 npm 包

检查 value 是否被归类为布尔基元或对象。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是布尔值,则返回 true,否则返回 false

例子

_.isBoolean(false);
// => true
 
_.isBoolean(null);
// => false

_.isBuffer(value)

源代码 npm 包

检查 value 是否为缓冲区。

4.3.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是缓冲区,则返回 true,否则返回 false

例子

_.isBuffer(new Buffer(2));
// => true
 
_.isBuffer(new Uint8Array(2));
// => false

_.isDate(value)

源代码 npm 包

检查 value 是否被归类为 Date 对象。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是日期对象,则返回 true,否则返回 false

例子

_.isDate(new Date);
// => true
 
_.isDate('Mon April 23 2012');
// => false

_.isElement(value)

源代码 npm 包

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

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是 DOM 元素,则返回 true,否则返回 false

例子

_.isElement(document.body);
// => true
 
_.isElement('<body>');
// => false

_.isEmpty(value)

源代码 npm 包

检查 value 是否为空对象、集合、映射或集。

如果对象没有自己的可枚举字符串键控属性,则该对象被视为为空。

如果类数组值(例如 arguments 对象、数组、缓冲区、字符串或类似 jQuery 的集合)的 length0,则该值被视为为空。类似地,如果映射和集的 size0,则它们也被视为为空。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 为空,则返回 true,否则返回 false

例子

_.isEmpty(null);
// => true
 
_.isEmpty(true);
// => true
 
_.isEmpty(1);
// => true
 
_.isEmpty([1, 2, 3]);
// => false
 
_.isEmpty({ 'a'1 });
// => false

_.isEqual(value, other)

源代码 npm 包

对两个值执行深度比较,以确定它们是否相等。

注意: 此方法支持比较数组、数组缓冲区、布尔值、日期对象、错误对象、映射、数字、Object 对象、正则表达式、集合、字符串、符号和类型化数组。Object 对象按其自身(而不是继承的)可枚举属性进行比较。函数和 DOM 节点通过严格相等进行比较,即 ===

0.1.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。

返回值

(布尔值): 如果值相等,则返回 true,否则返回 false

例子

var object = { 'a'1 };
var other = { 'a'1 };
 
_.isEqual(object, other);
// => true
 
object === other;
// => false

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

源代码 npm 包

此方法类似于 _.isEqual,不同之处在于它接受 customizer,该参数用于比较值。如果 customizer 返回 undefined,则由该方法处理比较。最多可以使用六个参数调用 customizer:*(objValue, othValue [, index|key, object, other, stack])*。

4.0.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。
  3. [customizer] (函数): 用于自定义比较的函数。

返回值

(布尔值): 如果值相等,则返回 true,否则返回 false

例子

function isGreeting(value) {
  return /^h(?:i|ello)$/.test(value);
}
 
function customizer(objValue, othValue) {
  if (isGreeting(objValue) && isGreeting(othValue)) {
    return true;
  }
}
 
var array = ['hello', 'goodbye'];
var other = ['hi', 'goodbye'];
 
_.isEqualWith(array, other, customizer);
// => true

_.isError(value)

源代码 npm 包

检查 value 是否为 ErrorEvalErrorRangeErrorReferenceErrorSyntaxErrorTypeErrorURIError 对象。

3.0.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是错误对象,则返回 true,否则返回 false

例子

_.isError(new Error);
// => true
 
_.isError(Error);
// => false

_.isFinite(value)

源代码 npm 包

检查 value 是否为有限基元数。

注意: 此方法基于 Number.isFinite

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是有限数,则返回 true,否则返回 false

例子

_.isFinite(3);
// => true
 
_.isFinite(Number.MIN_VALUE);
// => true
 
_.isFinite(Infinity);
// => false
 
_.isFinite('3');
// => false

_.isFunction(value)

源代码 npm 包

检查 value 是否被归类为 Function 对象。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是函数,则返回 true,否则返回 false

例子

_.isFunction(_);
// => true
 
_.isFunction(/abc/);
// => false

_.isInteger(value)

源代码 npm 包

检查 value 是否为整数。

注意: 此方法基于 Number.isInteger

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是整数,则返回 true,否则返回 false

例子

_.isInteger(3);
// => true
 
_.isInteger(Number.MIN_VALUE);
// => false
 
_.isInteger(Infinity);
// => false
 
_.isInteger('3');
// => false

_.isLength(value)

源代码 npm 包

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

注意: 此方法大致基于 ToLength

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是有效长度,则返回 true,否则返回 false

例子

_.isLength(3);
// => true
 
_.isLength(Number.MIN_VALUE);
// => false
 
_.isLength(Infinity);
// => false
 
_.isLength('3');
// => false

_.isMap(value)

源代码 npm 包

检查 value 是否被归类为 Map 对象。

4.3.0

参数

  1. value (*): 要检查的值。

返回值

(布尔值): 如果 value 是映射,则返回 true,否则返回 false

例子

_.isMap(new Map);
// => true
 
_.isMap(new WeakMap);
// => false

_.isMatch(object, source)

源代码 npm 包

objectsource 执行部分深度比较,以确定 object 是否包含等效的属性值。

注意:source 被部分应用时,此方法等同于 _.matches

部分比较将分别匹配空数组和空对象 source 值与任何数组或对象值。有关支持的值比较列表,请参阅 _.isEqual

3.0.0

参数

  1. object (对象): 要检查的对象。
  2. source (Object):要匹配的属性值对象。

返回值

(boolean):如果 object 匹配,则返回 true,否则返回 false

例子

var object = { 'a'1, 'b'2 };
 
_.isMatch(object, { 'b'2 });
// => true
 
_.isMatch(object, { 'b'1 });
// => false

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

源代码 npm 包

此方法类似于 _.isMatch,不同之处在于它接受 customizer,该参数用于比较值。如果 customizer 返回 undefined,则由该方法处理比较。customizer 使用五个参数调用:(objValue, srcValue, index|key, object, source)

4.0.0

参数

  1. object (对象): 要检查的对象。
  2. source (Object):要匹配的属性值对象。
  3. [customizer] (函数): 用于自定义比较的函数。

返回值

(boolean):如果 object 匹配,则返回 true,否则返回 false

例子

function isGreeting(value) {
  return /^h(?:i|ello)$/.test(value);
}
 
function customizer(objValue, srcValue) {
  if (isGreeting(objValue) && isGreeting(srcValue)) {
    return true;
  }
}
 
var object = { 'greeting''hello' };
var source = { 'greeting''hi' };
 
_.isMatchWith(object, source, customizer);
// => true

_.isNaN(value)

源代码 npm 包

检查 value 是否为 NaN

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

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 valueNaN,则返回 true,否则返回 false

例子

_.isNaN(NaN);
// => true
 
_.isNaN(new Number(NaN));
// => true
 
isNaN(undefined);
// => true
 
_.isNaN(undefined);
// => false

_.isNative(value)

源代码 npm 包

检查 value 是否为原始原生函数。

注意: 在存在 core-js 包的情况下,此方法无法可靠地检测原生函数,因为 core-js 绕过了这种检测。尽管多次请求,core-js 维护者已明确表示:任何修复检测的尝试都将受到阻挠。因此,我们别无选择,只能抛出错误。不幸的是,这也影响了依赖 core-js 的包,例如 babel-polyfill

3.0.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是原生函数,则返回 true,否则返回 false

例子

_.isNative(Array.prototype.push);
// => true
 
_.isNative(_);
// => false

_.isNil(value)

源代码 npm 包

检查 value 是否为 nullundefined

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 为 null 或 undefined,则返回 true,否则返回 false

例子

_.isNil(null);
// => true
 
_.isNil(void 0);
// => true
 
_.isNil(NaN);
// => false

_.isNull(value)

源代码 npm 包

检查 value 是否为 null

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 valuenull,则返回 true,否则返回 false

例子

_.isNull(null);
// => true
 
_.isNull(void 0);
// => false

_.isNumber(value)

源代码 npm 包

检查 value 是否分类为 Number 原语或对象。

注意: 要排除分类为数字的 Infinity-InfinityNaN,请使用 _.isFinite 方法。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是数字,则返回 true,否则返回 false

例子

_.isNumber(3);
// => true
 
_.isNumber(Number.MIN_VALUE);
// => true
 
_.isNumber(Infinity);
// => true
 
_.isNumber('3');
// => false

_.isObject(value)

源代码 npm 包

检查 value 是否为 Object语言类型(例如数组、函数、对象、正则表达式、new Number(0)new String('')

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是对象,则返回 true,否则返回 false

例子

_.isObject({});
// => true
 
_.isObject([1, 2, 3]);
// => true
 
_.isObject(_.noop);
// => true
 
_.isObject(null);
// => false

_.isObjectLike(value)

源代码 npm 包

检查 value 是否类似于对象。如果 value 不为 null 并且其 typeof 结果为“object”,则它类似于对象。

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 类似于对象,则返回 true,否则返回 false

例子

_.isObjectLike({});
// => true
 
_.isObjectLike([1, 2, 3]);
// => true
 
_.isObjectLike(_.noop);
// => false
 
_.isObjectLike(null);
// => false

_.isPlainObject(value)

源代码 npm 包

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

0.8.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是普通对象,则返回 true,否则返回 false

例子

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

_.isRegExp(value)

源代码 npm 包

检查 value 是否分类为 RegExp 对象。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是正则表达式,则返回 true,否则返回 false

例子

_.isRegExp(/abc/);
// => true
 
_.isRegExp('/abc/');
// => false

_.isSafeInteger(value)

源代码 npm 包

检查 value 是否为安全整数。如果整数是 IEEE-754 双精度浮点数,并且不是舍入后的不安全整数的结果,则该整数是安全的。

注意: 此方法基于 Number.isSafeInteger

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是安全整数,则返回 true,否则返回 false

例子

_.isSafeInteger(3);
// => true
 
_.isSafeInteger(Number.MIN_VALUE);
// => false
 
_.isSafeInteger(Infinity);
// => false
 
_.isSafeInteger('3');
// => false

_.isSet(value)

源代码 npm 包

检查 value 是否分类为 Set 对象。

4.3.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是集合,则返回 true,否则返回 false

例子

_.isSet(new Set);
// => true
 
_.isSet(new WeakSet);
// => false

_.isString(value)

源代码 npm 包

检查 value 是否分类为 String 原语或对象。

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是字符串,则返回 true,否则返回 false

例子

_.isString('abc');
// => true
 
_.isString(1);
// => false

_.isSymbol(value)

源代码 npm 包

检查 value 是否分类为 Symbol 原语或对象。

4.0.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是符号,则返回 true,否则返回 false

例子

_.isSymbol(Symbol.iterator);
// => true
 
_.isSymbol('abc');
// => false

_.isTypedArray(value)

源代码 npm 包

检查 value 是否分类为类型化数组。

3.0.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是类型化数组,则返回 true,否则返回 false

例子

_.isTypedArray(new Uint8Array);
// => true
 
_.isTypedArray([]);
// => false

_.isUndefined(value)

源代码 npm 包

检查 value 是否为 undefined

0.1.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 valueundefined,则返回 true,否则返回 false

例子

_.isUndefined(void 0);
// => true
 
_.isUndefined(null);
// => false

_.isWeakMap(value)

源代码 npm 包

检查 value 是否分类为 WeakMap 对象。

4.3.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是弱映射,则返回 true,否则返回 false

例子

_.isWeakMap(new WeakMap);
// => true
 
_.isWeakMap(new Map);
// => false

_.isWeakSet(value)

源代码 npm 包

检查 value 是否分类为 WeakSet 对象。

4.3.0

参数

  1. value (*): 要检查的值。

返回值

(boolean):如果 value 是弱集合,则返回 true,否则返回 false

例子

_.isWeakSet(new WeakSet);
// => true
 
_.isWeakSet(new Set);
// => false

_.lt(value, other)

源代码 npm 包

检查 value 是否小于 other

3.9.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。

返回值

(boolean):如果 value 小于 other,则返回 true,否则返回 false

例子

_.lt(1, 3);
// => true
 
_.lt(3, 3);
// => false
 
_.lt(3, 1);
// => false

_.lte(value, other)

源代码 npm 包

检查 value 是否小于或等于 other

3.9.0

参数

  1. value (*): 要比较的值。
  2. other (*): 要比较的另一个值。

返回值

(boolean):如果 value 小于或等于 other,则返回 true,否则返回 false

例子

_.lte(1, 3);
// => true
 
_.lte(3, 3);
// => true
 
_.lte(3, 1);
// => false

_.toArray(value)

源代码 npm 包

value 转换为数组。

0.1.0

参数

  1. value (*):要转换的值。

返回值

(Array):返回转换后的数组。

例子

_.toArray({ 'a'1, 'b'2 });
// => [1, 2]
 
_.toArray('abc');
// => ['a', 'b', 'c']
 
_.toArray(1);
// => []
 
_.toArray(null);
// => []

_.toFinite(value)

源代码 npm 包

value 转换为有限数。

4.12.0

参数

  1. value (*):要转换的值。

返回值

(number):返回转换后的数字。

例子

_.toFinite(3.2);
// => 3.2
 
_.toFinite(Number.MIN_VALUE);
// => 5e-324
 
_.toFinite(Infinity);
// => 1.7976931348623157e+308
 
_.toFinite('3.2');
// => 3.2

_.toInteger(value)

源代码 npm 包

value 转换为整数。

注意: 此方法大致基于 ToInteger

4.0.0

参数

  1. value (*):要转换的值。

返回值

(number):返回转换后的整数。

例子

_.toInteger(3.2);
// => 3
 
_.toInteger(Number.MIN_VALUE);
// => 0
 
_.toInteger(Infinity);
// => 1.7976931348623157e+308
 
_.toInteger('3.2');
// => 3

_.toLength(value)

源代码 npm 包

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

注意: 此方法基于 ToLength

4.0.0

参数

  1. value (*):要转换的值。

返回值

(number):返回转换后的整数。

例子

_.toLength(3.2);
// => 3
 
_.toLength(Number.MIN_VALUE);
// => 0
 
_.toLength(Infinity);
// => 4294967295
 
_.toLength('3.2');
// => 3

_.toNumber(value)

源代码 npm 包

value 转换为数字。

4.0.0

参数

  1. value (*):要处理的值。

返回值

(number):返回数字。

例子

_.toNumber(3.2);
// => 3.2
 
_.toNumber(Number.MIN_VALUE);
// => 5e-324
 
_.toNumber(Infinity);
// => Infinity
 
_.toNumber('3.2');
// => 3.2

_.toPlainObject(value)

源代码 npm 包

value 转换为普通对象,将 value 继承的可枚举字符串键控属性扁平化为普通对象的自身属性。

3.0.0

参数

  1. value (*):要转换的值。

返回值

(Object):返回转换后的普通对象。

例子

function Foo() {
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.assign({ 'a'1 }, new Foo);
// => { 'a': 1, 'b': 2 }
 
_.assign({ 'a'1 }, _.toPlainObject(new Foo));
// => { 'a': 1, 'b': 2, 'c': 3 }

_.toSafeInteger(value)

源代码 npm 包

value 转换为安全整数。安全整数可以正确比较和表示。

4.0.0

参数

  1. value (*):要转换的值。

返回值

(number):返回转换后的整数。

例子

_.toSafeInteger(3.2);
// => 3
 
_.toSafeInteger(Number.MIN_VALUE);
// => 0
 
_.toSafeInteger(Infinity);
// => 9007199254740991
 
_.toSafeInteger('3.2');
// => 3

_.toString(value)

源代码 npm 包

value 转换为字符串。对于 nullundefined 值,返回空字符串。保留 -0 的符号。

4.0.0

参数

  1. value (*):要转换的值。

返回值

(string):返回转换后的字符串。

例子

_.toString(null);
// => ''
 
_.toString(-0);
// => '-0'
 
_.toString([1, 2, 3]);
// => '1,2,3'

“数学”方法

_.add(augend, addend)

源代码 npm 包

将两个数字相加。

3.4.0

参数

  1. augend (number):加法中的第一个数字。
  2. addend (number):加法中的第二个数字。

返回值

(number):返回总和。

例子

_.add(6, 4);
// => 10

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

源代码 npm 包

计算 number 向上舍入到 precision 的值。

3.10.0

参数

  1. number (number):要向上舍入的数字。
  2. [precision=0] (number):向上舍入的精度。

返回值

(number):返回向上舍入后的数字。

例子

_.ceil(4.006);
// => 5
 
_.ceil(6.004, 2);
// => 6.01
 
_.ceil(6040, -2);
// => 6100

_.divide(dividend, divisor)

源代码 npm 包

将两个数字相除。

4.7.0

参数

  1. dividend (number):除法中的第一个数字。
  2. divisor (number):除法中的第二个数字。

返回值

(number):返回商。

例子

_.divide(6, 4);
// => 1.5

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

源代码 npm 包

计算 number 向下舍入到 precision 的值。

3.10.0

参数

  1. number (number):要向下舍入的数字。
  2. [precision=0] (数字): 要向下舍入的精度。

返回值

(数字): 返回向下舍入后的数字。

例子

_.floor(4.006);
// => 4
 
_.floor(0.046, 2);
// => 0.04
 
_.floor(4060, -2);
// => 4000

_.max(array)

源代码 npm 包

计算 array 的最大值。如果 array 为空或假值,则返回 undefined

0.1.0

参数

  1. array (数组): 要迭代的数组。

返回值

(*): 返回最大值。

例子

_.max([4, 2, 8, 6]);
// => 8
 
_.max([]);
// => undefined

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

源代码 npm 包

此方法类似于 _.max,不同之处在于它接受 iteratee,该参数为 array 中的每个元素调用,以生成用于对值进行排名的条件。使用一个参数调用 iteratee:(value)

4.0.0

参数

  1. array (数组): 要迭代的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(*): 返回最大值。

例子

var objects = [{ 'n'1 }, { 'n'2 }];
 
_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }
 
// The `_.property` iteratee shorthand.
_.maxBy(objects, 'n');
// => { 'n': 2 }

_.mean(array)

源代码 npm 包

计算 array 中值的平均值。

4.0.0

参数

  1. array (数组): 要迭代的数组。

返回值

(数字): 返回平均值。

例子

_.mean([4, 2, 8, 6]);
// => 5

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

源代码 npm 包

此方法类似于 _.mean,不同之处在于它接受 iteratee,该参数为 array 中的每个元素调用,以生成要计算平均值的值。使用一个参数调用 iteratee:(value)

4.7.0

参数

  1. array (数组): 要迭代的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(数字): 返回平均值。

例子

var objects = [{ 'n'4 }, { 'n'2 }, { 'n'8 }, { 'n'6 }];
 
_.meanBy(objects, function(o) { return o.n; });
// => 5
 
// The `_.property` iteratee shorthand.
_.meanBy(objects, 'n');
// => 5

_.min(array)

源代码 npm 包

计算 array 的最小值。如果 array 为空或假值,则返回 undefined

0.1.0

参数

  1. array (数组): 要迭代的数组。

返回值

(*): 返回最小值。

例子

_.min([4, 2, 8, 6]);
// => 2
 
_.min([]);
// => undefined

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

源代码 npm 包

此方法类似于 _.min,不同之处在于它接受 iteratee,该参数为 array 中的每个元素调用,以生成用于对值进行排名的条件。使用一个参数调用 iteratee:(value)

4.0.0

参数

  1. array (数组): 要迭代的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(*): 返回最小值。

例子

var objects = [{ 'n'1 }, { 'n'2 }];
 
_.minBy(objects, function(o) { return o.n; });
// => { 'n': 1 }
 
// The `_.property` iteratee shorthand.
_.minBy(objects, 'n');
// => { 'n': 1 }

_.multiply(multiplier, multiplicand)

源代码 npm 包

将两个数字相乘。

4.7.0

参数

  1. multiplier (数字): 乘法中的第一个数字。
  2. multiplicand (数字): 乘法中的第二个数字。

返回值

(数字): 返回乘积。

例子

_.multiply(6, 4);
// => 24

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

源代码 npm 包

计算将 number 四舍五入到 precision 位的结果。

3.10.0

参数

  1. number (数字): 要四舍五入的数字。
  2. [precision=0] (数字): 要四舍五入的精度。

返回值

(数字): 返回四舍五入后的数字。

例子

_.round(4.006);
// => 4
 
_.round(4.006, 2);
// => 4.01
 
_.round(4060, -2);
// => 4100

_.subtract(minuend, subtrahend)

源代码 npm 包

从一个数字中减去另一个数字。

4.0.0

参数

  1. minuend (数字): 减法中的第一个数字。
  2. subtrahend (数字): 减法中的第二个数字。

返回值

(数字): 返回差值。

例子

_.subtract(6, 4);
// => 2

_.sum(array)

源代码 npm 包

计算 array 中所有值的总和。

3.4.0

参数

  1. array (数组): 要迭代的数组。

返回值

(数字): 返回总和。

例子

_.sum([4, 2, 8, 6]);
// => 20

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

源代码 npm 包

此方法类似于 _.sum,不同之处在于它接受 iteratee,该参数为 array 中的每个元素调用,以生成要进行求和的值。使用一个参数调用 iteratee:(value)

4.0.0

参数

  1. array (数组): 要迭代的数组。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(数字): 返回总和。

例子

var objects = [{ 'n'4 }, { 'n'2 }, { 'n'8 }, { 'n'6 }];
 
_.sumBy(objects, function(o) { return o.n; });
// => 20
 
// The `_.property` iteratee shorthand.
_.sumBy(objects, 'n');
// => 20

“数字”方法

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

源代码 npm 包

number 限定在包含 lowerupper 边界的范围内。

4.0.0

参数

  1. number (数字): 要限定的数字。
  2. [lower] (数字): 下限。
  3. upper (数字): 上限。

返回值

(数字): 返回限定后的数字。

例子

_.clamp(-10, -5, 5);
// => -5
 
_.clamp(10, -5, 5);
// => 5

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

源代码 npm 包

检查 n 是否在 startend 之间(包含 start,但不包含 end)。如果未指定 end,则将其设置为 start,并将 start 设置为 0。如果 start 大于 end,则交换参数以支持负范围。

3.3.0

参数

  1. number (数字): 要检查的数字。
  2. [start=0] (数字): 范围的起始值。
  3. end (数字): 范围的结束值。

返回值

(布尔值): 如果 number 在范围内,则返回 true,否则返回 false

例子

_.inRange(3, 2, 4);
// => true
 
_.inRange(4, 8);
// => true
 
_.inRange(4, 2);
// => false
 
_.inRange(2, 2);
// => false
 
_.inRange(1.2, 2);
// => true
 
_.inRange(5.2, 4);
// => false
 
_.inRange(-3, -2, -6);
// => true

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

源代码 npm 包

生成一个介于包含 lowerupper 边界的随机数。如果只提供一个参数,则返回 0 和给定数字之间的数字。如果 floatingtrue,或者 lowerupper 是浮点数,则返回浮点数而不是整数。

注意: JavaScript 遵循 IEEE-754 标准来解析浮点值,这可能会产生意外结果。

0.7.0

参数

  1. [lower=0] (数字): 下限。
  2. [upper=1] (数字): 上限。
  3. [floating] (布尔值): 指定返回浮点数。

返回值

(数字): 返回随机数。

例子

_.random(0, 5);
// => an integer between 0 and 5
 
_.random(5);
// => also an integer between 0 and 5
 
_.random(5, true);
// => a floating-point number between 0 and 5
 
_.random(1.2, 5.2);
// => a floating-point number between 1.2 and 5.2

“对象”方法

_.assign(object, [sources])

源代码 npm 包

将源对象的自身可枚举字符串键属性分配给目标对象。源对象从左到右应用。后续源会覆盖先前源的属性分配。

注意: 此方法会改变 object,并且大致基于 Object.assign

0.10.0

参数

  1. object (对象): 目标对象。
  2. [sources] (...对象): 源对象。

返回值

(对象): 返回 object

例子

function Foo() {
  this.a = 1;
}
 
function Bar() {
  this.c = 3;
}
 
Foo.prototype.b = 2;
Bar.prototype.d = 4;
 
_.assign({ 'a'0 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3 }

_.assignIn(object, [sources])

源代码 npm 包

此方法类似于 _.assign,不同之处在于它迭代自身和继承的源属性。

注意: 此方法会改变 object

4.0.0

别名

_.extend

参数

  1. object (对象): 目标对象。
  2. [sources] (...对象): 源对象。

返回值

(对象): 返回 object

例子

function Foo() {
  this.a = 1;
}
 
function Bar() {
  this.c = 3;
}
 
Foo.prototype.b = 2;
Bar.prototype.d = 4;
 
_.assignIn({ 'a'0 }, new Foo, new Bar);
// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }

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

源代码 npm 包

此方法类似于 _.assignIn,不同之处在于它接受 customizer,该参数用于生成分配的值。如果 customizer 返回 undefined,则由该方法处理分配。使用五个参数调用 customizer(objValue, srcValue, key, object, source)

注意: 此方法会改变 object

4.0.0

别名

_.extendWith

参数

  1. object (对象): 目标对象。
  2. sources (...对象): 源对象。
  3. [customizer] (函数): 用于自定义分配值的函数。

返回值

(对象): 返回 object

例子

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

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

源代码 npm 包

此方法类似于 _.assign,不同之处在于它接受 customizer,该参数用于生成分配的值。如果 customizer 返回 undefined,则由该方法处理分配。使用五个参数调用 customizer(objValue, srcValue, key, object, source)

注意: 此方法会改变 object

4.0.0

参数

  1. object (对象): 目标对象。
  2. sources (...对象): 源对象。
  3. [customizer] (函数): 用于自定义分配值的函数。

返回值

(对象): 返回 object

例子

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

_.at(object, [paths])

源代码 npm 包

创建一个与 objectpaths 对应的值数组。

1.0.0

参数

  1. object (对象): 要迭代的对象。
  2. [paths] (...(字符串|字符串[])): 要选择的属性路径。

返回值

(数组): 返回选定的值。

例子

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

_.create(prototype, [properties])

源代码 npm 包

创建一个继承自 prototype 对象的对象。如果给定了 properties 对象,则将其自身可枚举字符串键属性分配给创建的对象。

2.3.0

参数

  1. prototype (对象): 要继承的对象。
  2. [properties] (对象): 要分配给对象的属性。

返回值

(Object):返回新对象。

例子

function Shape() {
  this.x = 0;
  this.y = 0;
}
 
function Circle() {
  Shape.call(this);
}
 
Circle.prototype = _.create(Shape.prototype, {
  'constructor': Circle
});
 
var circle = new Circle;
circle instanceof Circle;
// => true
 
circle instanceof Shape;
// => true

_.defaults(object, [sources])

源代码 npm 包

将源对象的自身和继承的可枚举字符串键属性分配给目标对象,用于解析为 undefined 的所有目标属性。源对象从左到右应用。设置属性后,将忽略相同属性的其他值。

注意: 此方法会改变 object

0.1.0

参数

  1. object (对象): 目标对象。
  2. [sources] (...对象): 源对象。

返回值

(对象): 返回 object

例子

_.defaults({ 'a'1 }, { 'b'2 }, { 'a'3 });
// => { 'a': 1, 'b': 2 }

_.defaultsDeep(object, [sources])

源代码 npm 包

此方法类似于 _.defaults,不同之处在于它递归地分配默认属性。

注意: 此方法会改变 object

3.10.0

参数

  1. object (对象): 目标对象。
  2. [sources] (...对象): 源对象。

返回值

(对象): 返回 object

例子

_.defaultsDeep({ 'a': { 'b'2 } }, { 'a': { 'b'1, 'c'3 } });
// => { 'a': { 'b': 2, 'c': 3 } }

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

源代码 npm 包

此方法类似于 _.find,不同之处在于它返回 predicate 返回真值的第一个元素的键,而不是元素本身。

1.1.0

参数

  1. object (对象): 要检查的对象。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(*): 返回匹配元素的键,否则返回 undefined

例子

var users = {
  'barney':  { 'age'36, 'active': true },
  'fred':    { 'age'40, 'active': false },
  'pebbles': { 'age'1,  'active': true }
};
 
_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)
 
// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age'1, 'active': true });
// => 'pebbles'
 
// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'
 
// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'

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

源代码 npm 包

此方法类似于 _.findKey,不同之处在于它以相反的顺序迭代集合的元素。

2.0.0

参数

  1. object (对象): 要检查的对象。
  2. [predicate=_.identity] (Function): 每次迭代调用的函数。

返回值

(*): 返回匹配元素的键,否则返回 undefined

例子

var users = {
  'barney':  { 'age'36, 'active': true },
  'fred':    { 'age'40, 'active': false },
  'pebbles': { 'age'1,  'active': true }
};
 
_.findLastKey(users, function(o) { return o.age < 40; });
// => returns 'pebbles' assuming `_.findKey` returns 'barney'
 
// The `_.matches` iteratee shorthand.
_.findLastKey(users, { 'age'36, 'active': true });
// => 'barney'
 
// The `_.matchesProperty` iteratee shorthand.
_.findLastKey(users, ['active', false]);
// => 'fred'
 
// The `_.property` iteratee shorthand.
_.findLastKey(users, 'active');
// => 'pebbles'

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

源代码 npm 包

迭代对象自身和继承的可枚举字符串键属性,并为每个属性调用 iteratee。使用三个参数调用 iteratee:(value, key, object)。Iteratee 函数可以通过显式返回 false 来提前退出迭代。

0.3.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(对象): 返回 object

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.forIn(new Foo, function(value, key) {
  console.log(key);
});
// => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).

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

源代码 npm 包

此方法类似于 _.forIn,不同之处在于它以相反的顺序迭代 object 的属性。

2.0.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(对象): 返回 object

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.forInRight(new Foo, function(value, key) {
  console.log(key);
});
// => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.

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

源代码 npm 包

迭代对象自身可枚举字符串键属性,并为每个属性调用 iteratee。使用三个参数调用 iteratee:(value, key, object)。Iteratee 函数可以通过显式返回 false 来提前退出迭代。

0.3.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(对象): 返回 object

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.forOwn(new Foo, function(value, key) {
  console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).

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

源代码 npm 包

此方法类似于 _.forOwn,不同之处在于它以相反的顺序迭代 object 的属性。

2.0.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(对象): 返回 object

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.forOwnRight(new Foo, function(value, key) {
  console.log(key);
});
// => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.

_.functions(object)

源代码 npm 包

object 自身可枚举属性中创建函数属性名称数组。

0.1.0

参数

  1. object (对象): 要检查的对象。

返回值

(数组):返回函数名。

例子

function Foo() {
  this.a = _.constant('a');
  this.b = _.constant('b');
}
 
Foo.prototype.c = _.constant('c');
 
_.functions(new Foo);
// => ['a', 'b']

_.functionsIn(object)

源代码 npm 包

创建一个数组,其中包含 object 自身和继承的可枚举属性的函数属性名。

4.0.0

参数

  1. object (对象): 要检查的对象。

返回值

(数组):返回函数名。

例子

function Foo() {
  this.a = _.constant('a');
  this.b = _.constant('b');
}
 
Foo.prototype.c = _.constant('c');
 
_.functionsIn(new Foo);
// => ['a', 'b', 'c']

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

源代码 npm 包

获取 objectpath 路径上的值。如果解析后的值为 undefined,则返回 defaultValue

3.7.0

参数

  1. object (对象):要查询的对象。
  2. path (数组|字符串):要获取的属性的路径。
  3. [defaultValue] (*):解析后的值为 undefined 时返回的值。

返回值

(*):返回解析后的值。

例子

var object = { 'a': [{ 'b': { 'c'3 } }] };
 
_.get(object, 'a[0].b.c');
// => 3
 
_.get(object, ['a', '0', 'b', 'c']);
// => 3
 
_.get(object, 'a.b.c', 'default');
// => 'default'

_.has(object, path)

源代码 npm 包

检查 path 是否为 object 的直接属性。

0.1.0

参数

  1. object (对象):要查询的对象。
  2. path (数组|字符串):要检查的路径。

返回值

(布尔值):如果 path 存在,则返回 true,否则返回 false

例子

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

_.hasIn(object, path)

源代码 npm 包

检查 path 是否为 object 的直接或继承属性。

4.0.0

参数

  1. object (对象):要查询的对象。
  2. path (数组|字符串):要检查的路径。

返回值

(布尔值):如果 path 存在,则返回 true,否则返回 false

例子

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

_.invert(object)

源代码 npm 包

创建一个由 object 的键值对反转后的对象。如果 object 包含重复值,则后续值将覆盖先前值的属性赋值。

0.7.0

参数

  1. object (对象):要反转的对象。

返回值

(对象):返回新的反转对象。

例子

var object = { 'a'1, 'b'2, 'c'1 };
 
_.invert(object);
// => { '1': 'c', '2': 'b' }

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

源代码 npm 包

此方法类似于 _.invert,不同之处在于,反转后的对象是通过对 object 的每个元素运行 iteratee 生成的。每个反转键对应的反转值是一个数组,其中包含生成该反转值的键。迭代函数使用一个参数调用:(value)

4.1.0

参数

  1. object (对象):要反转的对象。
  2. [iteratee=_.identity] (Function): 每次迭代调用的迭代函数。

返回值

(对象):返回新的反转对象。

例子

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

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

源代码 npm 包

调用 objectpath 路径上的方法。

4.0.0

参数

  1. object (对象):要查询的对象。
  2. path (数组|字符串):要调用的方法的路径。
  3. [args] (...*):调用方法时要使用的参数。

返回值

(*):返回调用方法的结果。

例子

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

_.keys(object)

源代码 npm 包

创建一个数组,其中包含 object 自身可枚举属性的名称。

**注意:**非对象值将被强制转换为对象。有关更多详细信息,请参阅 ES 规范

0.1.0

参数

  1. object (对象):要查询的对象。

返回值

(数组):返回属性名称数组。

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.keys(new Foo);
// => ['a', 'b'] (iteration order is not guaranteed)
 
_.keys('hi');
// => ['0', '1']

_.keysIn(object)

源代码 npm 包

创建一个数组,其中包含 object 自身和继承的可枚举属性的名称。

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

3.0.0

参数

  1. object (对象):要查询的对象。

返回值

(数组):返回属性名称数组。

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.keysIn(new Foo);
// => ['a', 'b', 'c'] (iteration order is not guaranteed)

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

源代码 npm 包

_.mapValues 的反向操作;此方法创建一个与 object 具有相同值的对象,并通过对 object 的每个自身可枚举字符串键控属性运行 iteratee 来生成键。迭代函数使用三个参数调用:(value,key,object)

3.8.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(对象):返回新的映射对象。

例子

_.mapKeys({ 'a'1, 'b'2 }, function(value, key) {
  return key + value;
});
// => { 'a1': 1, 'b2': 2 }

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

源代码 npm 包

创建一个与 object 具有相同键的对象,并通过对 object 的每个自身可枚举字符串键控属性运行 iteratee 来生成值。迭代函数使用三个参数调用:
(value,key,object).

2.4.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(对象):返回新的映射对象。

例子

var users = {
  'fred':    { 'user''fred',    'age'40 },
  'pebbles': { 'user''pebbles', 'age'1 }
};
 
_.mapValues(users, function(o) { return o.age; });
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
 
// The `_.property` iteratee shorthand.
_.mapValues(users, 'age');
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)

_.merge(object, [sources])

源代码 npm 包

此方法类似于 _.assign,不同之处在于,它递归地将源对象的自身和继承的可枚举字符串键控属性合并到目标对象中。如果目标值存在,则解析为 undefined 的源属性将被跳过。数组和普通对象属性将递归合并。其他对象和值类型将被赋值覆盖。源对象从左到右应用。后续源将覆盖先前源的属性赋值。

注意: 此方法会改变 object

0.5.0

参数

  1. object (对象): 目标对象。
  2. [sources] (...对象): 源对象。

返回值

(对象): 返回 object

例子

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

_.mergeWith(object, sources, customizer)

源代码 npm 包

此方法类似于 _.merge,不同之处在于,它接受 customizer 参数,该参数用于生成目标属性和源属性的合并值。如果 customizer 返回 undefined,则合并将由该方法处理。customizer 使用六个参数调用:
(objValue,srcValue,key,object,source,stack).

注意: 此方法会改变 object

4.0.0

参数

  1. object (对象): 目标对象。
  2. sources (...对象): 源对象。
  3. customizer (函数):用于自定义赋值的函数。

返回值

(对象): 返回 object

例子

function customizer(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
}
 
var object = { 'a': [1], 'b': [2] };
var other = { 'a': [3], 'b': [4] };
 
_.mergeWith(object, other, customizer);
// => { 'a': [1, 3], 'b': [2, 4] }

_.omit(object, [paths])

源代码 npm 包

_.pick 的反向操作;此方法创建一个对象,该对象由 object 中未被省略的自身和继承的可枚举属性路径组成。

**注意:**此方法比 _.pick 慢得多。

0.1.0

参数

  1. object (对象):源对象。
  2. [paths] (...(字符串|字符串数组)):要省略的属性路径。

返回值

(Object):返回新对象。

例子

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

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

源代码 npm 包

_.pickBy 的反向操作;此方法创建一个对象,该对象由 objectpredicate 不返回真值的自身和继承的可枚举字符串键控属性组成。谓词使用两个参数调用:(value,key)

4.0.0

参数

  1. object (对象):源对象。
  2. [predicate=_.identity] (函数):每个属性调用的函数。

返回值

(Object):返回新对象。

例子

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

_.pick(object, [paths])

源代码 npm 包

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

0.1.0

参数

  1. object (对象):源对象。
  2. [paths] (...(字符串|字符串[])): 要选择的属性路径。

返回值

(Object):返回新对象。

例子

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

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

源代码 npm 包

创建一个由 objectpredicate 返回真值的属性组成的新对象。谓词使用两个参数调用:(value,key)

4.0.0

参数

  1. object (对象):源对象。
  2. [predicate=_.identity] (函数):每个属性调用的函数。

返回值

(Object):返回新对象。

例子

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

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

源代码 npm 包

此方法类似于 _.get,不同之处在于,如果解析后的值是一个函数,则将使用其父对象的 this 绑定调用该函数,并返回其结果。

0.1.0

参数

  1. object (对象):要查询的对象。
  2. path (数组|字符串):要解析的属性的路径。
  3. [defaultValue] (*):解析后的值为 undefined 时返回的值。

返回值

(*):返回解析后的值。

例子

var object = { 'a': [{ 'b': { 'c1'3, 'c2': _.constant(4) } }] };
 
_.result(object, 'a[0].b.c1');
// => 3
 
_.result(object, 'a[0].b.c2');
// => 4
 
_.result(object, 'a[0].b.c3', 'default');
// => 'default'
 
_.result(object, 'a[0].b.c3', _.constant('default'));
// => 'default'

_.set(object, path, value)

源代码 npm 包

设置 objectpath 路径上的值。如果 path 的一部分不存在,则创建它。对于缺少的索引属性,将创建数组,而对于所有其他缺少的属性,将创建对象。使用 _.setWith 自定义 path 的创建。

注意: 此方法会改变 object

3.7.0

参数

  1. object (对象):要修改的对象。
  2. path (数组|字符串):要设置的属性的路径。
  3. value (*):要设置的值。

返回值

(对象): 返回 object

例子

var object = { 'a': [{ 'b': { 'c'3 } }] };
 
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
 
_.set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5

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

源代码 npm 包

此方法类似于 _.set,不同之处在于,它接受 customizer 参数,该参数用于生成 path 的对象。如果 customizer 返回 undefined,则路径创建将由该方法处理。customizer 使用三个参数调用:(nsValue,key,nsObject)

注意: 此方法会改变 object

4.0.0

参数

  1. object (对象):要修改的对象。
  2. path (数组|字符串):要设置的属性的路径。
  3. value (*):要设置的值。
  4. [customizer] (函数): 用于自定义分配值的函数。

返回值

(对象): 返回 object

例子

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

_.toPairs(object)

源代码 npm 包

object 创建一个由自身可枚举字符串键控的键值对组成的数组,该数组可以被 _.fromPairs 使用。如果 object 是映射或集合,则返回其条目。

4.0.0

别名

_.entries

参数

  1. object (对象):要查询的对象。

返回值

(数组):返回键值对。

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.toPairs(new Foo);
// => [['a', 1], ['b', 2]] (iteration order is not guaranteed)

_.toPairsIn(object)

源代码 npm 包

object 创建一个由自身和继承的可枚举字符串键控的键值对组成的数组,该数组可以被 _.fromPairs 使用。如果 object 是映射或集合,则返回其条目。

4.0.0

别名

_.entriesIn

参数

  1. object (对象):要查询的对象。

返回值

(数组):返回键值对。

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.toPairsIn(new Foo);
// => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)

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

源代码 npm 包

_.reduce 的替代方法;此方法将 object 转换为新的 accumulator 对象,该对象是通过对 object 的每个自身可枚举字符串键控属性运行 iteratee 的结果,每次调用都可能改变 accumulator 对象。如果没有提供 accumulator,则将使用具有相同 [[Prototype]] 的新对象。迭代函数使用四个参数调用:(accumulator,value,key,object)。迭代函数可以通过显式返回 false 来提前退出迭代。

1.3.0

参数

  1. object (对象): 要迭代的对象。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。
  3. [accumulator] (*):自定义累加器值。

返回值

(*):返回累积值。

例子

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

_.unset(object, path)

源代码 npm 包

删除 objectpath 路径上的属性。

注意: 此方法会改变 object

4.0.0

参数

  1. object (对象):要修改的对象。
  2. path (数组|字符串):要删除的属性的路径。

返回值

(布尔值):如果属性已删除,则返回 true,否则返回 false

例子

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

_.update(object, path, updater)

源代码 npm 包

此方法类似于 _.set,不同之处在于,它接受 updater 参数来生成要设置的值。使用 _.updateWith 自定义 path 的创建。updater 使用一个参数调用:(value)

注意: 此方法会改变 object

4.6.0

参数

  1. object (对象):要修改的对象。
  2. path (数组|字符串):要设置的属性的路径。
  3. updater (函数):用于生成更新值的函数。

返回值

(对象): 返回 object

例子

var object = { 'a': [{ 'b': { 'c'3 } }] };
 
_.update(object, 'a[0].b.c', function(n) { return n * n; });
console.log(object.a[0].b.c);
// => 9
 
_.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
console.log(object.x[0].y.z);
// => 0

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

源代码 npm 包

此方法类似于 _.update,不同之处在于,它接受 customizer 参数,该参数用于生成 path 的对象。如果 customizer 返回 undefined,则路径创建将由该方法处理。customizer 使用三个参数调用:(nsValue,key,nsObject)

注意: 此方法会改变 object

4.6.0

参数

  1. object (对象):要修改的对象。
  2. path (数组|字符串):要设置的属性的路径。
  3. updater (函数):用于生成更新值的函数。
  4. [customizer] (函数): 用于自定义分配值的函数。

返回值

(对象): 返回 object

例子

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

_.values(object)

源代码 npm 包

创建一个数组,其中包含 object 自身可枚举字符串键控属性的值。

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

0.1.0

参数

  1. object (对象):要查询的对象。

返回值

(数组):返回属性值数组。

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.values(new Foo);
// => [1, 2] (iteration order is not guaranteed)
 
_.values('hi');
// => ['h', 'i']

_.valuesIn(object)

源代码 npm 包

创建一个由 object 自身和继承的可枚举字符串键值组成的数组。

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

3.0.0

参数

  1. object (对象):要查询的对象。

返回值

(数组):返回属性值数组。

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
Foo.prototype.c = 3;
 
_.valuesIn(new Foo);
// => [1, 2, 3] (iteration order is not guaranteed)

“Seq” 方法

_(value)

来源

创建一个包装 valuelodash 对象,以启用隐式方法链序列。可以将对数组、集合和函数进行操作并返回相同类型的方法链接在一起。检索单个值或可能返回原始值的方法将自动结束链序列并返回解包后的值。否则,必须使用 _#value 解包该值。

可以使用 _.chain 启用必须使用 _#value 解包的显式链序列。

链式方法的执行是惰性的,也就是说,它会延迟到隐式或显式调用 _#value 时才执行。

惰性求值允许几种方法支持快捷融合。快捷融合是一种优化,用于合并迭代器调用;这避免了创建中间数组,并且可以大大减少迭代器执行的次数。如果链序列的一部分应用于数组并且迭代器只接受一个参数,则该部分符合快捷融合的条件。关于某个部分是否符合快捷融合条件的启发式方法可能会发生变化。

只要 _#value 方法直接或间接包含在构建中,自定义构建就支持链式操作。

除了 lodash 方法之外,包装器还具有 ArrayString 方法。

包装器 Array 方法有:
concatjoinpoppushshiftsortspliceunshift

包装器 String 方法有:
replacesplit

支持快捷融合的包装器方法有:
atcompactdropdropRightdropWhilefilterfindfindLastheadinitiallastmaprejectreverseslicetailtaketakeRighttakeRightWhiletakeWhiletoArray

可链接的包装器方法有:
afteraryassignassignInassignInWithassignWithatbeforebindbindAllbindKeycastArraychainchunkcommitcompactconcatconformsconstantcountBycreatecurrydebouncedefaultsdefaultsDeepdeferdelaydifferencedifferenceBydifferenceWithdropdropRightdropRightWhiledropWhileextendextendWithfillfilterflatMapflatMapDeepflatMapDepthflattenflattenDeepflattenDepthflipflowflowRightfromPairsfunctionsfunctionsIngroupByinitialintersectionintersectionByintersectionWithinvertinvertByinvokeMapiterateekeyBykeyskeysInmapmapKeysmapValuesmatchesmatchesPropertymemoizemergemergeWithmethodmethodOfmixinnegatenthArgomitomitByonceorderByoveroverArgsoverEveryoverSomepartialpartialRightpartitionpickpickByplantpropertypropertyOfpullpullAllpullAllBypullAllWithpullAtpushrangerangeRightreargrejectremoverestreversesampleSizesetsetWithshuffleslicesortsortBysplicespreadtailtaketakeRighttakeRightWhiletakeWhiletapthrottlethrutoArraytoPairstoPairsIntoPathtoPlainObjecttransformunaryunionunionByunionWithuniquniqByuniqWithunsetunshiftunzipunzipWithupdateupdateWithvaluesvaluesInwithoutwrapxorxorByxorWithzipzipObjectzipObjectDeepzipWith

默认情况下**不可**链接的包装器方法有:
addattemptcamelCasecapitalizeceilclampclonecloneDeepcloneDeepWithcloneWithconformsTodeburrdefaultTodivideeacheachRightendsWitheqescapeescapeRegExpeveryfindfindIndexfindKeyfindLastfindLastIndexfindLastKeyfirstfloorforEachforEachRightforInforInRightforOwnforOwnRightgetgtgtehashasInheadidentityincludesindexOfinRangeinvokeisArgumentsisArrayisArrayBufferisArrayLikeisArrayLikeObjectisBooleanisBufferisDateisElementisEmptyisEqualisEqualWithisErrorisFiniteisFunctionisIntegerisLengthisMapisMatchisMatchWithisNaNisNativeisNilisNullisNumberisObjectisObjectLikeisPlainObjectisRegExpisSafeIntegerisSetisStringisUndefinedisTypedArrayisWeakMapisWeakSetjoinkebabCaselastlastIndexOflowerCaselowerFirstltltemaxmaxBymeanmeanByminminBymultiplynoConflictnoopnownthpadpadEndpadStartparseIntpoprandomreducereduceRightrepeatresultroundrunInContextsampleshiftsizesnakeCasesomesortedIndexsortedIndexBysortedLastIndexsortedLastIndexBystartCasestartsWithstubArraystubFalsestubObjectstubStringstubTruesubtractsumsumBytemplatetimestoFinitetoIntegertoJSONtoLengthtoLowertoNumbertoSafeIntegertoStringtoUppertrimtrimEndtrimStarttruncateunescapeuniqueIdupperCaseupperFirstvaluewords

参数

  1. value (*):要包装在 lodash 实例中的值。

返回值

(Object):返回新的 lodash 包装器实例。

例子

function square(n) {
  return n * n;
}
 
var wrapped = _([1, 2, 3]);
 
// Returns an unwrapped value.
wrapped.reduce(_.add);
// => 6
 
// Returns a wrapped value.
var squares = wrapped.map(square);
 
_.isArray(squares);
// => false
 
_.isArray(squares.value());
// => true

_.chain(value)

来源

创建一个 lodash 包装器实例,该实例包装 value 并启用显式方法链序列。此类序列的结果必须使用 _#value 解包。

1.3.0

参数

  1. value (*): 要包装的值。

返回值

(Object):返回新的 lodash 包装器实例。

例子

var users = [
  { 'user''barney',  'age'36 },
  { 'user''fred',    'age'40 },
  { 'user''pebbles', 'age'1 }
];
 
var youngest = _
  .chain(users)
  .sortBy('age')
  .map(function(o) {
    return o.user + ' is ' + o.age;
  })
  .head()
  .value();
// => 'pebbles is 1'

_.tap(value, interceptor)

来源

此方法调用 interceptor 并返回 value。使用一个参数调用拦截器;(value)。此方法的目的是“插入”方法链序列以修改中间结果。

0.1.0

参数

  1. value (*):要提供给 interceptor 的值。
  2. interceptor (Function):要调用的函数。

返回值

(*):返回 value

例子

_([1, 2, 3])
 .tap(function(array) {
// Mutate input array.
   array.pop();
 })
 .reverse()
 .value();
// => [2, 1]

_.thru(value, interceptor)

来源

此方法类似于 _.tap,不同之处在于它返回 interceptor 的结果。此方法的目的是“传递”值,替换方法链序列中的中间结果。

3.0.0

参数

  1. value (*):要提供给 interceptor 的值。
  2. interceptor (Function):要调用的函数。

返回值

(*):返回 interceptor 的结果。

例子

_('  abc  ')
 .chain()
 .trim()
 .thru(function(value) {
   return [value];
 })
 .value();
// => ['abc']

_.prototype[Symbol.iterator]()

来源

使包装器可迭代。

4.0.0

返回值

(Object):返回包装器对象。

例子

var wrapped = _([1, 2]);
 
wrapped[Symbol.iterator]() === wrapped;
// => true
 
Array.from(wrapped);
// => [1, 2]

_.prototype.at([paths])

来源

此方法是 _.at 的包装器版本。

1.0.0

参数

  1. [paths] (...(字符串|字符串[])): 要选择的属性路径。

返回值

(Object):返回新的 lodash 包装器实例。

例子

var object = { 'a': [{ 'b': { 'c'3 } }, 4] };
 
_(object).at(['a[0].b.c', 'a[1]']).value();
// => [3, 4]

_.prototype.chain()

来源

创建一个启用了显式方法链序列的 lodash 包装器实例。

0.1.0

返回值

(Object):返回新的 lodash 包装器实例。

例子

var users = [
  { 'user''barney', 'age'36 },
  { 'user''fred',   'age'40 }
];
 
// A sequence without explicit chaining.
_(users).head();
// => { 'user': 'barney', 'age': 36 }
 
// A sequence with explicit chaining.
_(users)
  .chain()
  .head()
  .pick('user')
  .value();
// => { 'user': 'barney' }

_.prototype.commit()

来源

执行链序列并返回包装的结果。

3.2.0

返回值

(Object):返回新的 lodash 包装器实例。

例子

var array = [1, 2];
var wrapped = _(array).push(3);
 
console.log(array);
// => [1, 2]
 
wrapped = wrapped.commit();
console.log(array);
// => [1, 2, 3]
 
wrapped.last();
// => 3
 
console.log(array);
// => [1, 2, 3]

_.prototype.next()

来源

按照 迭代器协议 获取包装对象上的下一个值。

4.0.0

返回值

(Object):返回下一个迭代器值。

例子

var wrapped = _([1, 2]);
 
wrapped.next();
// => { 'done': false, 'value': 1 }
 
wrapped.next();
// => { 'done': false, 'value': 2 }
 
wrapped.next();
// => { 'done': true, 'value': undefined }

_.prototype.plant(value)

来源

创建链序列的克隆,将 value 作为包装值。

3.2.0

参数

  1. value (*):要设置的值。

返回值

(Object):返回新的 lodash 包装器实例。

例子

function square(n) {
  return n * n;
}
 
var wrapped = _([1, 2]).map(square);
var other = wrapped.plant([3, 4]);
 
other.value();
// => [9, 16]
 
wrapped.value();
// => [1, 4]

_.prototype.reverse()

来源

此方法是 _.reverse 的包装器版本。

**注意:**此方法会改变包装的数组。

0.1.0

返回值

(Object):返回新的 lodash 包装器实例。

例子

var array = [1, 2, 3];
 
_(array).reverse().value()
// => [3, 2, 1]
 
console.log(array);
// => [3, 2, 1]

_.prototype.value()

来源

执行链序列以解析解包后的值。

0.1.0

别名

_.prototype.toJSON, _.prototype.valueOf

返回值

(*):返回解析后的解包值。

例子

_([1, 2, 3]).value();
// => [1, 2, 3]

“字符串”方法

_.camelCase([string=''])

来源 npm 包

string 转换为 驼峰式大小写

3.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回驼峰式大小写的字符串。

例子

_.camelCase('Foo Bar');
// => 'fooBar'
 
_.camelCase('--foo-bar--');
// => 'fooBar'
 
_.camelCase('__FOO_BAR__');
// => 'fooBar'

_.capitalize([string=''])

来源 npm 包

string 的第一个字符转换为大写,其余字符转换为小写。

3.0.0

参数

  1. [string=''] (string):要首字母大写的字符串。

返回值

(string):返回首字母大写的字符串。

例子

_.capitalize('FRED');
// => 'Fred'

_.deburr([string=''])

来源 npm 包

通过将 拉丁字母-1 补充拉丁字母扩展-A 字母转换为基本拉丁字母并删除 组合用上标 来去除 string 中的特殊符号。

3.0.0

参数

  1. [string=''] (string):要去除特殊符号的字符串。

返回值

(string):返回去除特殊符号后的字符串。

例子

_.deburr('déjà vu');
// => 'deja vu'

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

来源 npm 包

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

3.0.0

参数

  1. [string=''] (string):要检查的字符串。
  2. [target] (string):要搜索的字符串。
  3. [position=string.length] (number):要搜索到的位置。

返回值

(boolean):如果 stringtarget 结尾,则返回 true,否则返回 false

例子

_.endsWith('abc', 'c');
// => true
 
_.endsWith('abc', 'b');
// => false
 
_.endsWith('abc', 'b', 2);
// => true

_.escape([string=''])

来源 npm 包

string 中的字符“&”、“<”、“>”、“'”和“"”转换为其对应的 HTML 实体。

**注意:**不会转义其他字符。要转义其他字符,请使用第三方库,例如 he

尽管出于对称性考虑,字符“>”会被转义,但像“>”和“/”这样的字符在 HTML 中不需要转义,并且除非它们是标签或未加引号的属性值的一部分,否则没有特殊含义。有关更多详细信息,请参阅 Mathias Bynens 的文章(“半相关趣闻”下)。

使用 HTML 时,应始终 对属性值加引号,以减少 XSS 攻击向量。

0.1.0

参数

  1. [string=''] (string):要转义的字符串。

返回值

(string):返回转义后的字符串。

例子

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

_.escapeRegExp([string=''])

来源 npm 包

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

3.0.0

参数

  1. [string=''] (string):要转义的字符串。

返回值

(string):返回转义后的字符串。

例子

_.escapeRegExp('[lodash](https://lodash.node.org.cn/)');
// => '\[lodash\]\(https://lodash\.com/\)'

_.kebabCase([string=''])

来源 npm 包

string 转换为 烤肉串式大小写

3.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回烤肉串式大小写的字符串。

例子

_.kebabCase('Foo Bar');
// => 'foo-bar'
 
_.kebabCase('fooBar');
// => 'foo-bar'
 
_.kebabCase('__FOO_BAR__');
// => 'foo-bar'

_.lowerCase([string=''])

源代码 npm 包

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

4.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回转换为小写的字符串。

例子

_.lowerCase('--Foo-Bar--');
// => 'foo bar'
 
_.lowerCase('fooBar');
// => 'foo bar'
 
_.lowerCase('__FOO_BAR__');
// => 'foo bar'

_.lowerFirst([string=''])

源代码 npm 包

string 的第一个字符转换为小写。

4.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回转换后的字符串。

例子

_.lowerFirst('Fred');
// => 'fred'
 
_.lowerFirst('FRED');
// => 'fRED'

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

源代码 npm 包

如果 stringlength 短,则在其左侧和右侧填充字符。 如果填充字符不能被 length 整除,则将截断它们。

3.0.0

参数

  1. [string=''] (string):要填充的字符串。
  2. [length=0] (number):填充长度。
  3. [chars=' '] (string):用作填充的字符串。

返回值

(string):返回填充后的字符串。

例子

_.pad('abc', 8);
// => '  abc   '
 
_.pad('abc', 8, '_-');
// => '_-abc_-_'
 
_.pad('abc', 3);
// => 'abc'

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

源代码 npm 包

如果 stringlength 短,则在其右侧填充字符。 如果填充字符超过 length,则将截断它们。

4.0.0

参数

  1. [string=''] (string):要填充的字符串。
  2. [length=0] (number):填充长度。
  3. [chars=' '] (string):用作填充的字符串。

返回值

(string):返回填充后的字符串。

例子

_.padEnd('abc', 6);
// => 'abc   '
 
_.padEnd('abc', 6, '_-');
// => 'abc_-_'
 
_.padEnd('abc', 3);
// => 'abc'

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

源代码 npm 包

如果 stringlength 短,则在其左侧填充字符。 如果填充字符超过 length,则将截断它们。

4.0.0

参数

  1. [string=''] (string):要填充的字符串。
  2. [length=0] (number):填充长度。
  3. [chars=' '] (string):用作填充的字符串。

返回值

(string):返回填充后的字符串。

例子

_.padStart('abc', 6);
// => '   abc'
 
_.padStart('abc', 6, '_-');
// => '_-_abc'
 
_.padStart('abc', 3);
// => 'abc'

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

源代码 npm 包

string 转换为指定进制的整数。 如果 radixundefined0,则使用 10 进制,除非 value 是十六进制,在这种情况下使用 16 进制。

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

1.1.0

参数

  1. string (string):要转换的字符串。
  2. [radix=10] (number):解释 value 的进制。

返回值

(number):返回转换后的整数。

例子

_.parseInt('08');
// => 8
 
_.map(['6', '08', '10'], _.parseInt);
// => [6, 8, 10]

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

源代码 npm 包

将给定的字符串 string 重复 n 次。

3.0.0

参数

  1. [string=''] (string):要重复的字符串。
  2. [n=1] (number):重复字符串的次数。

返回值

(string):返回重复后的字符串。

例子

_.repeat('*', 3);
// => '***'
 
_.repeat('abc', 2);
// => 'abcabc'
 
_.repeat('abc', 0);
// => ''

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

源代码 npm 包

string 中与 pattern 匹配的内容替换为 replacement

注意: 此方法基于 String#replace

4.0.0

参数

  1. [string=''] (string):要修改的字符串。
  2. pattern (RegExp|string):要替换的模式。
  3. replacement (Function|string):匹配的替换内容。

返回值

(string):返回修改后的字符串。

例子

_.replace('Hi Fred', 'Fred', 'Barney');
// => 'Hi Barney'

_.snakeCase([string=''])

源代码 npm 包

string 转换为 蛇形命名法

3.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回蛇形命名法的字符串。

例子

_.snakeCase('Foo Bar');
// => 'foo_bar'
 
_.snakeCase('fooBar');
// => 'foo_bar'
 
_.snakeCase('--FOO-BAR--');
// => 'foo_bar'

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

源代码 npm 包

separator 拆分 string

注意: 此方法基于 String#split

4.0.0

参数

  1. [string=''] (string):要拆分的字符串。
  2. separator (RegExp|string):用于拆分的分割符模式。
  3. [limit] (number):要截断结果的长度。

返回值

(Array):返回字符串段。

例子

_.split('a-b-c', '-', 2);
// => ['a', 'b']

_.startCase([string=''])

源代码 npm 包

string 转换为 首字母大写

3.1.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回首字母大写的字符串。

例子

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'

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

源代码 npm 包

检查 string 是否以给定的目标字符串开头。

3.0.0

参数

  1. [string=''] (string):要检查的字符串。
  2. [target] (string):要搜索的字符串。
  3. [position=0] (number):开始搜索的位置。

返回值

(boolean):如果 stringtarget 开头,则返回 true,否则返回 false

例子

_.startsWith('abc', 'a');
// => true
 
_.startsWith('abc', 'b');
// => false
 
_.startsWith('abc', 'b', 1);
// => true

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

源代码 npm 包

创建一个已编译的模板函数,该函数可以在“插值”分隔符中插入数据属性,在“转义”分隔符中对插入的数据属性进行 HTML 转义,并在“求值”分隔符中执行 JavaScript。 数据属性可以在模板中作为自由变量访问。 如果给定了设置对象,则它优先于 _.templateSettings 值。

注意: 在开发版本中,_.template 利用 源代码 URL 来简化调试。

有关预编译模板的更多信息,请参阅 lodash 的自定义构建文档

有关 Chrome 扩展沙箱的更多信息,请参阅 Chrome 的扩展文档

0.1.0

参数

  1. [string=''] (string):模板字符串。
  2. [options={}] (对象):选项对象。
  3. [options.escape=_.templateSettings.escape] (RegExp):HTML“转义”分隔符。
  4. [options.evaluate=_.templateSettings.evaluate] (RegExp):“求值”分隔符。
  5. [options.imports=_.templateSettings.imports] (Object):要作为自由变量导入模板的对象。
  6. [options.interpolate=_.templateSettings.interpolate] (RegExp):“插值”分隔符。
  7. [options.sourceURL='lodash.templateSources[n]'] (string):已编译模板的源代码 URL。
  8. [options.variable='obj'] (string):数据对象变量名称。

返回值

(Function):返回已编译的模板函数。

例子

// Use the "interpolate" delimiter to create a compiled template.
var compiled = _.template('hello <%= user %>!');
compiled({ 'user''fred' });
// => 'hello fred!'
 
// Use the HTML "escape" delimiter to escape data property values.
var compiled = _.template('<b><%- value %></b>');
compiled({ 'value''<script>' });
// => '<b>&lt;script&gt;</b>'
 
// Use the "evaluate" delimiter to execute JavaScript and generate HTML.
var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
 
// Use the internal `print` function in "evaluate" delimiters.
var compiled = _.template('<% print("hello " + user); %>!');
compiled({ 'user''barney' });
// => 'hello barney!'
 
// Use the ES template literal delimiter as an "interpolate" delimiter.
// Disable support by replacing the "interpolate" delimiter.
var compiled = _.template('hello ${ user }!');
compiled({ 'user''pebbles' });
// => 'hello pebbles!'
 
// Use backslashes to treat delimiters as plain text.
var compiled = _.template('<%= "\\<%- value %\\>" %>');
compiled({ 'value''ignored' });
// => '<%- value %>'
 
// Use the `imports` option to import `jQuery` as `jq`.
var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
 
// Use the `sourceURL` option to specify a custom sourceURL for the template.
var compiled = _.template('hello <%= user %>!', { 'sourceURL''/basic/greeting.jst' });
compiled(data);
// => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
 
// Use the `variable` option to ensure a with-statement isn't used in the compiled template.
var compiled = _.template('hi <%= data.user %>!', { 'variable''data' });
compiled.source;
// => function(data) {
//   var __t, __p = '';
//   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
//   return __p;
// }
 
// Use custom template delimiters.
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user''mustache' });
// => 'hello mustache!'
 
// Use the `source` property to inline compiled templates for meaningful
// line numbers in error messages and stack traces.
fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
  var JST = {\
    "main": ' + _.template(mainText).source + '\
  };\
');

_.toLower([string=''])

源代码 npm 包

string 整体转换为小写,就像 String#toLowerCase 一样。

4.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回转换为小写的字符串。

例子

_.toLower('--Foo-Bar--');
// => '--foo-bar--'
 
_.toLower('fooBar');
// => 'foobar'
 
_.toLower('__FOO_BAR__');
// => '__foo_bar__'

_.toUpper([string=''])

源代码 npm 包

string 整体转换为大写,就像 String#toUpperCase 一样。

4.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回转换为大写的字符串。

例子

_.toUpper('--foo-bar--');
// => '--FOO-BAR--'
 
_.toUpper('fooBar');
// => 'FOOBAR'
 
_.toUpper('__foo_bar__');
// => '__FOO_BAR__'

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

源代码 npm 包

string 中删除开头和结尾的空格或指定字符。

3.0.0

参数

  1. [string=''] (string):要修剪的字符串。
  2. [chars=whitespace] (string):要修剪的字符。

返回值

(string):返回修剪后的字符串。

例子

_.trim('  abc  ');
// => 'abc'
 
_.trim('-_-abc-_-', '_-');
// => 'abc'
 
_.map(['  foo  ', '  bar  '], _.trim);
// => ['foo', 'bar']

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

源代码 npm 包

string 中删除结尾的空格或指定字符。

4.0.0

参数

  1. [string=''] (string):要修剪的字符串。
  2. [chars=whitespace] (string):要修剪的字符。

返回值

(string):返回修剪后的字符串。

例子

_.trimEnd('  abc  ');
// => '  abc'
 
_.trimEnd('-_-abc-_-', '_-');
// => '-_-abc'

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

源代码 npm 包

string 中删除开头的空格或指定字符。

4.0.0

参数

  1. [string=''] (string):要修剪的字符串。
  2. [chars=whitespace] (string):要修剪的字符。

返回值

(string):返回修剪后的字符串。

例子

_.trimStart('  abc  ');
// => 'abc  '
 
_.trimStart('-_-abc-_-', '_-');
// => 'abc-_-'

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

源代码 npm 包

如果 string 超过给定的最大字符串长度,则将其截断。 截断后的字符串的最后几个字符将替换为省略号字符串,默认为“...”。

4.0.0

参数

  1. [string=''] (string):要截断的字符串。
  2. [options={}] (对象):选项对象。
  3. [options.length=30] (number):最大字符串长度。
  4. [options.omission='...'] (string):指示文本被省略的字符串。
  5. [options.separator] (RegExp|string):要截断到的分隔符模式。

返回值

(string):返回截断后的字符串。

例子

_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'
 
_.truncate('hi-diddly-ho there, neighborino', {
  'length'24,
  'separator'' '
});
// => 'hi-diddly-ho there,...'
 
_.truncate('hi-diddly-ho there, neighborino', {
  'length'24,
  'separator': /,? +/
});
// => 'hi-diddly-ho there...'
 
_.truncate('hi-diddly-ho there, neighborino', {
  'omission'' [...]'
});
// => 'hi-diddly-ho there, neig [...]'

_.unescape([string=''])

源代码 npm 包

_.escape 的逆运算;此方法将 string 中的 HTML 实体 &amp;&lt;&gt;&quot;&#39; 转换为其对应的字符。

注意: 没有其他 HTML 实体被反转义。 要反转义其他 HTML 实体,请使用第三方库,例如 he

0.6.0

参数

  1. [string=''] (string):要反转义的字符串。

返回值

(string):返回反转义后的字符串。

例子

_.unescape('fred, barney, &amp; pebbles');
// => 'fred, barney, & pebbles'

_.upperCase([string=''])

源代码 npm 包

string(以空格分隔的单词)转换为大写。

4.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回转换为大写的字符串。

例子

_.upperCase('--foo-bar');
// => 'FOO BAR'
 
_.upperCase('fooBar');
// => 'FOO BAR'
 
_.upperCase('__foo_bar__');
// => 'FOO BAR'

_.upperFirst([string=''])

源代码 npm 包

string 的第一个字符转换为大写。

4.0.0

参数

  1. [string=''] (string):要转换的字符串。

返回值

(string):返回转换后的字符串。

例子

_.upperFirst('fred');
// => 'Fred'
 
_.upperFirst('FRED');
// => 'FRED'

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

源代码 npm 包

string 拆分为单词数组。

3.0.0

参数

  1. [string=''] (string):要检查的字符串。
  2. [pattern] (RegExp|string):匹配单词的模式。

返回值

(Array):返回 string 的单词。

例子

_.words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']
 
_.words('fred, barney, & pebbles', /[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']

“实用工具”方法

_.attempt(func, [args])

源代码 npm 包

尝试调用 func,返回结果或捕获的错误对象。 调用 func 时,会向其提供任何其他参数。

3.0.0

参数

  1. func (Function):要尝试的函数。
  2. [args] (...*):用于调用 func 的参数。

返回值

(*):返回 func 结果或错误对象。

例子

// Avoid throwing errors for invalid selectors.
var elements = _.attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');
 
if (_.isError(elements)) {
  elements = [];
}

_.bindAll(object, methodNames)

源代码 npm 包

将对象的方法绑定到对象本身,覆盖现有方法。

注意: 此方法不会设置绑定函数的“length”属性。

0.1.0

参数

  1. object (Object):要绑定并将绑定方法分配到的对象。
  2. methodNames (...(string|string[])):要绑定的对象方法名称。

返回值

(对象): 返回 object

例子

var view = {
  'label''docs',
  'click'function() {
    console.log('clicked ' + this.label);
  }
};
 
_.bindAll(view, ['click']);
jQuery(element).on('click', view.click);
// => Logs 'clicked docs' when clicked.

_.cond(pairs)

源代码 npm 包

创建一个函数,该函数迭代 pairs 并调用第一个返回真值的谓词的对应函数。 使用创建函数的 this 绑定和参数调用谓词-函数对。

4.0.0

参数

  1. 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 });
// => 'matches A'
 
func({ 'a'0, 'b'1 });
// => 'matches B'
 
func({ 'a''1', 'b''2' });
// => 'no match'

_.conforms(source)

源代码 npm 包

创建一个函数,该函数使用给定对象的相应属性值调用 source 的谓词属性,如果所有谓词都返回真值,则返回 true,否则返回 false

注意: 创建的函数等效于部分应用了 source_.conformsTo

4.0.0

参数

  1. source (对象): 要符合的属性谓词对象。

返回值

(Function):返回新的规范函数。

例子

var objects = [
  { 'a'2, 'b'1 },
  { 'a'1, 'b'2 }
];
 
_.filter(objects, _.conforms({ 'b'function(n) { return n > 1; } }));
// => [{ 'a': 1, 'b': 2 }]

_.constant(value)

源代码 npm 包

创建一个返回 value 的函数。

2.4.0

参数

  1. value (*):要从新函数返回的值。

返回值

(函数):返回新的常量函数。

例子

var objects = _.times(2, _.constant({ 'a'1 }));
 
console.log(objects);
// => [{ 'a': 1 }, { 'a': 1 }]
 
console.log(objects[0] === objects[1]);
// => true

_.defaultTo(value, defaultValue)

源代码 npm 包

检查 value 以确定是否应返回默认值。如果 valueNaNnullundefined,则返回 defaultValue

4.14.0

参数

  1. value (*): 要检查的值。
  2. defaultValue (*):默认值。

返回值

(*):返回解析后的值。

例子

_.defaultTo(1, 10);
// => 1
 
_.defaultTo(undefined, 10);
// => 10

_.flow([funcs])

源代码 npm 包

创建一个函数,该函数使用创建函数的 this 绑定调用给定函数并返回结果,其中每个后续调用都提供前一个调用的返回值。

3.0.0

参数

  1. [funcs] (...(Function|Function[])):要调用的函数。

返回值

(Function):返回新的组合函数。

例子

function square(n) {
  return n * n;
}
 
var addSquare = _.flow([_.add, square]);
addSquare(1, 2);
// => 9

_.flowRight([funcs])

源代码 npm 包

此方法类似于 _.flow,不同之处在于它创建的函数从右到左调用给定的函数。

3.0.0

参数

  1. [funcs] (...(Function|Function[])):要调用的函数。

返回值

(Function):返回新的组合函数。

例子

function square(n) {
  return n * n;
}
 
var addSquare = _.flowRight([square, _.add]);
addSquare(1, 2);
// => 9

_.identity(value)

源代码 npm 包

此方法返回它接收到的第一个参数。

0.1.0

参数

  1. value (*):任意值。

返回值

(*):返回 value

例子

var object = { 'a'1 };
 
console.log(_.identity(object) === object);
// => true

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

源代码 npm 包

创建一个函数,该函数使用创建函数的参数调用 func。如果 func 是属性名称,则创建的函数返回给定元素的属性值。如果 func 是数组或对象,则创建的函数对于包含等效源属性的元素返回 true,否则返回 false

4.0.0

参数

  1. [func=_.identity] (*):要转换为回调的值。

返回值

(函数):返回回调。

例子

var users = [
  { 'user''barney', 'age'36, 'active': true },
  { 'user''fred',   'age'40, 'active': false }
];
 
// The `_.matches` iteratee shorthand.
_.filter(users, _.iteratee({ 'user''barney', 'active': true }));
// => [{ 'user': 'barney', 'age': 36, 'active': true }]
 
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, _.iteratee(['user', 'fred']));
// => [{ 'user': 'fred', 'age': 40 }]
 
// The `_.property` iteratee shorthand.
_.map(users, _.iteratee('user'));
// => ['barney', 'fred']
 
// Create custom iteratee shorthands.
_.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  return !_.isRegExp(func) ? iteratee(func) : function(string) {
    return func.test(string);
  };
});
 
_.filter(['abc', 'def'], /ef/);
// => ['def']

_.matches(source)

源代码 npm 包

创建一个函数,该函数在给定对象和 source 之间执行部分深度比较,如果给定对象具有等效的属性值,则返回 true,否则返回 false

注意: 创建的函数等效于部分应用了 source_.isMatch

部分比较将分别匹配空数组和空对象 source 值与任何数组或对象值。有关支持的值比较列表,请参阅 _.isEqual

3.0.0

参数

  1. source (Object):要匹配的属性值对象。

返回值

(Function):返回新的规范函数。

例子

var objects = [
  { 'a'1, 'b'2, 'c'3 },
  { 'a'4, 'b'5, 'c'6 }
];
 
_.filter(objects, _.matches({ 'a'4, 'c'6 }));
// => [{ 'a': 4, 'b': 5, 'c': 6 }]

_.matchesProperty(path, srcValue)

源代码 npm 包

创建一个函数,该函数在给定对象的 path 处的属性值和 srcValue 之间执行部分深度比较,如果对象值相等,则返回 true,否则返回 false

注意: 部分比较会将空数组和空对象 srcValue 值分别与任何数组或对象值进行匹配。有关支持的值比较的列表,请参阅 _.isEqual

3.2.0

参数

  1. path (数组|字符串):要获取的属性的路径。
  2. srcValue (*):要匹配的值。

返回值

(Function):返回新的规范函数。

例子

var objects = [
  { 'a'1, 'b'2, 'c'3 },
  { 'a'4, 'b'5, 'c'6 }
];
 
_.find(objects, _.matchesProperty('a', 4));
// => { 'a': 4, 'b': 5, 'c': 6 }

_.method(path, [args])

源代码 npm 包

创建一个函数,该函数调用给定对象 path 处的方法。任何其他参数都将提供给调用的方法。

3.7.0

参数

  1. path (数组|字符串):要调用的方法的路径。
  2. [args] (...*):调用方法时要使用的参数。

返回值

(函数):返回新的调用器函数。

例子

var objects = [
  { 'a': { 'b': _.constant(2) } },
  { 'a': { 'b': _.constant(1) } }
];
 
_.map(objects, _.method('a.b'));
// => [2, 1]
 
_.map(objects, _.method(['a', 'b']));
// => [2, 1]

_.methodOf(object, [args])

源代码 npm 包

_.method 相反;此方法创建一个函数,该函数调用 object 给定路径处的方法。任何其他参数都将提供给调用的方法。

3.7.0

参数

  1. object (对象):要查询的对象。
  2. [args] (...*):调用方法时要使用的参数。

返回值

(函数):返回新的调用器函数。

例子

var array = _.times(3, _.constant),
    object = { 'a': array, 'b': array, 'c': array };
 
_.map(['a[2]', 'c[0]'], _.methodOf(object));
// => [2, 0]
 
_.map([['a', '2'], ['c', '0']], _.methodOf(object));
// => [2, 0]

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

源代码 npm 包

将源对象的所有可枚举字符串键控函数属性添加到目标对象。如果 object 是函数,则方法也会添加到其原型中。

注意: 使用 _.runInContext 创建一个原始的 lodash 函数,以避免修改原始函数导致的冲突。

0.1.0

参数

  1. [object=lodash] (Function|Object):目标对象。
  2. source (Object):要添加的函数对象。
  3. [options={}] (对象):选项对象。
  4. [options.chain=true] (boolean):指定混合是否可链接。

返回值

(*):返回 object

例子

function vowels(string) {
  return _.filter(string, function(v) {
    return /[aeiou]/i.test(v);
  });
}
 
_.mixin({ 'vowels': vowels });
_.vowels('fred');
// => ['e']
 
_('fred').vowels().value();
// => ['e']
 
_.mixin({ 'vowels': vowels }, { 'chain': false });
_('fred').vowels();
// => ['e']

_.noConflict()

源代码 npm 包

_ 变量恢复为其先前值,并返回对 lodash 函数的引用。

0.1.0

返回值

(函数):返回 lodash 函数。

例子

var lodash = _.noConflict();

_.noop()

源代码 npm 包

此方法返回 undefined

2.3.0

例子

_.times(2, _.noop);
// => [undefined, undefined]

_.nthArg([n=0])

源代码 npm 包

创建一个函数,该函数获取索引 n 处的参数。如果 n 为负数,则返回从末尾开始的第 n 个参数。

4.0.0

参数

  1. [n=0] (number):要返回的参数的索引。

返回值

(函数):返回新的传递函数。

例子

var func = _.nthArg(1);
func('a', 'b', 'c', 'd');
// => 'b'
 
var func = _.nthArg(-2);
func('a', 'b', 'c', 'd');
// => 'c'

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

源代码 npm 包

创建一个函数,该函数使用它接收到的参数调用 iteratees 并返回其结果。

4.0.0

参数

  1. [iteratees=[_.identity]] (...(Function|Function[])):要调用的迭代器。

返回值

(函数):返回新函数。

例子

var func = _.over([Math.max, Math.min]);
 
func(1, 2, 3, 4);
// => [4, 1]

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

源代码 npm 包

创建一个函数,该函数检查使用它接收到的参数调用时,所有 predicates 是否都返回真值。

4.0.0

参数

  1. [predicates=[_.identity]] (...(Function|Function[])):要检查的谓词。

返回值

(函数):返回新函数。

例子

var func = _.overEvery([Boolean, isFinite]);
 
func('1');
// => true
 
func(null);
// => false
 
func(NaN);
// => false

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

源代码 npm 包

创建一个函数,该函数检查使用它接收到的参数调用时,任何 predicates 是否都返回真值。

4.0.0

参数

  1. [predicates=[_.identity]] (...(Function|Function[])):要检查的谓词。

返回值

(函数):返回新函数。

例子

var func = _.overSome([Boolean, isFinite]);
 
func('1');
// => true
 
func(null);
// => true
 
func(NaN);
// => false

_.property(path)

源代码 npm 包

创建一个函数,该函数返回给定对象 path 处的值。

2.4.0

参数

  1. path (数组|字符串):要获取的属性的路径。

返回值

(函数):返回新的访问器函数。

例子

var objects = [
  { 'a': { 'b'2 } },
  { 'a': { 'b'1 } }
];
 
_.map(objects, _.property('a.b'));
// => [2, 1]
 
_.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
// => [1, 2]

_.propertyOf(object)

源代码 npm 包

_.property 相反;此方法创建一个函数,该函数返回 object 给定路径处的值。

3.0.0

参数

  1. object (对象):要查询的对象。

返回值

(函数):返回新的访问器函数。

例子

var array = [0, 1, 2],
    object = { 'a': array, 'b': array, 'c': array };
 
_.map(['a[2]', 'c[0]'], _.propertyOf(object));
// => [2, 0]
 
_.map([['a', '2'], ['c', '0']], _.propertyOf(object));
// => [2, 0]

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

源代码 npm 包

创建一个数字数组 (正数和/或负数),从 start 开始递增,直到但不包括 end。如果指定了负 start 且没有指定 endstep,则使用步长 -1。如果未指定 end,则将其设置为 start,并将 start 设置为 0

注意: JavaScript 遵循 IEEE-754 标准来解析浮点值,这可能会产生意外结果。

0.1.0

参数

  1. [start=0] (数字): 范围的起始值。
  2. end (数字): 范围的结束值。
  3. [step=1] (number):递增或递减的值。

返回值

(数组):返回数字范围。

例子

_.range(4);
// => [0, 1, 2, 3]
 
_.range(-4);
// => [0, -1, -2, -3]
 
_.range(1, 5);
// => [1, 2, 3, 4]
 
_.range(0, 20, 5);
// => [0, 5, 10, 15]
 
_.range(0, -4, -1);
// => [0, -1, -2, -3]
 
_.range(1, 4, 0);
// => [1, 1, 1]
 
_.range(0);
// => []

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

源代码 npm 包

此方法类似于 _.range,不同之处在于它按降序填充值。

4.0.0

参数

  1. [start=0] (数字): 范围的起始值。
  2. end (数字): 范围的结束值。
  3. [step=1] (number):递增或递减的值。

返回值

(数组):返回数字范围。

例子

_.rangeRight(4);
// => [3, 2, 1, 0]
 
_.rangeRight(-4);
// => [-3, -2, -1, 0]
 
_.rangeRight(1, 5);
// => [4, 3, 2, 1]
 
_.rangeRight(0, 20, 5);
// => [15, 10, 5, 0]
 
_.rangeRight(0, -4, -1);
// => [-3, -2, -1, 0]
 
_.rangeRight(1, 4, 0);
// => [1, 1, 1]
 
_.rangeRight(0);
// => []

_.runInContext([context=root])

源代码 npm 包

使用 context 对象创建一个新的原始 lodash 函数。

1.1.0

参数

  1. [context=root] (Object):上下文对象。

返回值

(函数):返回一个新的 lodash 函数。

例子

_.mixin({ 'foo': _.constant('foo') });
 
var lodash = _.runInContext();
lodash.mixin({ 'bar': lodash.constant('bar') });
 
_.isFunction(_.foo);
// => true
_.isFunction(_.bar);
// => false
 
lodash.isFunction(lodash.foo);
// => false
lodash.isFunction(lodash.bar);
// => true
 
// Create a suped-up `defer` in Node.js.
var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;

_.stubArray()

源代码 npm 包

此方法返回一个新的空数组。

4.13.0

返回值

(数组):返回新的空数组。

例子

var arrays = _.times(2, _.stubArray);
 
console.log(arrays);
// => [[], []]
 
console.log(arrays[0] === arrays[1]);
// => false

_.stubFalse()

源代码 npm 包

此方法返回 false

4.13.0

返回值

(布尔值):返回 false

例子

_.times(2, _.stubFalse);
// => [false, false]

_.stubObject()

源代码 npm 包

此方法返回一个新的空对象。

4.13.0

返回值

(对象):返回新的空对象。

例子

var objects = _.times(2, _.stubObject);
 
console.log(objects);
// => [{}, {}]
 
console.log(objects[0] === objects[1]);
// => false

_.stubString()

源代码 npm 包

此方法返回一个空字符串。

4.13.0

返回值

(字符串):返回空字符串。

例子

_.times(2, _.stubString);
// => ['', '']

_.stubTrue()

源代码 npm 包

此方法返回 true

4.13.0

返回值

(布尔值):返回 true

例子

_.times(2, _.stubTrue);
// => [true, true]

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

源代码 npm 包

调用迭代器 n 次,返回每次调用结果的数组。迭代器使用一个参数调用;(索引)

0.1.0

参数

  1. n (number):调用 iteratee 的次数。
  2. [iteratee=_.identity] (函数): 每次迭代调用的函数。

返回值

(Array):返回结果数组。

例子

_.times(3, String);
// => ['0', '1', '2']
 
 _.times(4, _.constant(0));
// => [0, 0, 0, 0]

_.toPath(value)

源代码 npm 包

value 转换为属性路径数组。

4.0.0

参数

  1. value (*):要转换的值。

返回值

(数组):返回新的属性路径数组。

例子

_.toPath('a.b.c');
// => ['a', 'b', 'c']
 
_.toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']

_.uniqueId([prefix=''])

源代码 npm 包

生成唯一 ID。如果给定了 prefix,则 ID 会附加到它后面。

0.1.0

参数

  1. [prefix=''] (string):用于前缀 ID 的值。

返回值

(字符串):返回唯一 ID。

例子

_.uniqueId('contact_');
// => 'contact_104'
 
_.uniqueId();
// => '105'

属性

_.VERSION

来源

(字符串):语义版本号。

_.templateSettings

源代码 npm 包

(对象):默认情况下,lodash 使用的模板分隔符类似于嵌入式 Ruby (ERB) 以及 ES2015 模板字符串中的分隔符。更改以下模板设置以使用其他分隔符。

_.templateSettings.escape

来源

(正则表达式):用于检测要进行 HTML 转义的 data 属性值。

_.templateSettings.evaluate

来源

(正则表达式):用于检测要评估的代码。

_.templateSettings.imports

来源

(对象):用于将变量导入到编译的模板中。

_.templateSettings.interpolate

来源

(正则表达式):用于检测要注入的 data 属性值。

_.templateSettings.variable

来源

(字符串):用于在模板文本中引用数据对象。

方法

_.templateSettings.imports._

来源

lodash 函数的引用。