lodash v3.10.1

Array

Chain

Collection

Date

Function

Lang

Math

Number

Object

String

Utility

Methods

Properties

“Array” Methods

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

#

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

参数

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

返回值

(Array): 返回一个包含拆分块数组的新数组(相当于一个二维数组)。

例子

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

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

_.compact(array)

#

创建一个新数组并包含原数组中所有的非假值元素。例如 falsenull0""undefinedNaN 都是“假值”。

参数

  1. array (Array): 数组参数.

返回值

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

例子

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

_.difference(array, [values])

#

Creates an array of unique array values not included in the other provided arrays using SameValueZero for equality comparisons.

参数

  1. array (Array): 需要过滤的数组
  2. [values] (...Array): 数组需要排除掉的值

返回值

(Array): 返回过滤后的数组

例子

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

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

#

array 中的前 n 个元素去掉,然后返回剩余的部分。

参数

  1. array (Array): 被操作的数组。
  2. [n=1] (number): 去掉的元素个数。

返回值

(Array): 返回 array 的剩余部分。

例子

_.drop([1, 2, 3]);
// => [2, 3] 默认是1开始的

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

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

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

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

#

array 尾部的 n 个元素去除,并返回剩余的部分。

参数

  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], [thisArg])

#

从尾端查询(右数)数组 array ,第一个不满足predicate 条件的元素开始截取数组. thisArgpredicate 条件执行上下文对象绑定的参数 .

参数 predicate 提供的是一个属性名称,就通过提供的参数使用 _.property方法返回一个回调函数

如果参数thisArg提供的话,就使用 _.matchesProperty方法匹配相同的属性值,相同返回true,不同返回false

如果参数predicate提供的是一个对象,就使用 _.matches方法匹配相同的元素,相同返回true,不同返回false

参数

  1. array (Array): 需要查询的数组
  2. [predicate=_.identity] (Function|Object|string): 数组迭代判断条件
  3. [thisArg] (*): 对应 predicate 属性的值.

返回值

(Array): 返回截取元素后的数组

例子

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

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// => ['barney', 'fred']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.dropRightWhile(users, 'active', false), 'user');
// => ['barney']

// using the `_.property` callback shorthand
_.pluck(_.dropRightWhile(users, 'active'), 'user');
// => ['barney', 'fred', 'pebbles']

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

#

从开头查询(左数起)数组 array ,第一个不满足predicate 条件的元素开始截取数组. thisArgpredicate 条件执行上下文对象绑定的参数 .

参数 predicate 提供的是一个属性名称,就通过提供的参数使用 _.property方法返回一个回调函数

如果参数thisArg提供的话,就使用 _.matchesProperty方法匹配相同的属性值,相同返回true,不同返回false

如果参数predicate提供的是一个对象,就使用 _.matches方法匹配相同的元素,相同返回true,不同返回false

参数

  1. array (Array): 需要查询的数组
  2. [predicate=_.identity] (Function|Object|string): 数组遍历的条件
  3. [thisArg] (*): 对应 predicate 属性的值.

返回值

(Array): 返回截取元素后的数组

例子

_.dropWhile([1, 2, 3], function(n) {
  return n < 3;
});
// => [3]

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

// using the `_.matches` callback shorthand
_.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
// => ['fred', 'pebbles']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.dropWhile(users, 'active', false), 'user');
// => ['pebbles']

// using the `_.property` callback shorthand
_.pluck(_.dropWhile(users, 'active'), 'user');
// => ['barney', 'fred', 'pebbles']

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

#

使用 value 值来填充(也就是替换) array,从start位置开始, 到end位置结束(但不包含end位置)

Note: 这是个改变数组的方法

参数

  1. array (Array): 需要填充的数组.
  2. value (*): 填充 array 元素的值.
  3. [start=0] (number): 起始位置(包含)
  4. [end=array.length] (number): 结束位置(不含)

返回值

(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], '*', 1, 2);
// => [4, '*', 8]

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

#

该方法类似 _.find,区别是该方法返回的是符合 predicate条件的第一个元素的索引,而不是返回元素本身.

参数 predicate 提供的是一个属性名称,就通过提供的参数使用 _.property方法返回一个回调函数

如果参数thisArg值提供的话,就使用 _.matchesProperty方法匹配相同的属性值,相同返回true,不同返回false

如果参数predicate提供的是一个对象,就使用 _.matches方法匹配相同的元素,相同返回true,不同返回false

参数

  1. array (Array): 需要搜索的数组
  2. [predicate=_.identity] (Function|Object|string): 数组遍历满足的条件
  3. [thisArg] (*): 对应 predicate 属性的值.

返回值

(number): 返回符合查询条件的元素的索引值, 未找到则返回 -1.

例子

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(chr) {
  return chr.user == 'barney';
});
// => 0

// using the `_.matches` callback shorthand
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// using the `_.matchesProperty` callback shorthand
_.findIndex(users, 'active', false);
// => 0

// using the `_.property` callback shorthand
_.findIndex(users, 'active');
// => 2

_.findLastIndex(array, [predicate=_.identity], [thisArg])

#

该方法类似 _.findIndex ,区别是其从右到左遍历数组.

该方法类似 _.find,区别是该方法返回的是符合 predicate条件的第一个元素的索引,而不是返回元素本身.

参数 predicate 提供的是一个属性名称,就通过提供的参数使用 _.property方法返回一个回调函数

如果参数thisArg值提供的话,就使用 _.matchesProperty方法匹配相同的属性值,相同返回true,不同返回false

如果参数predicate提供的是一个对象,就使用 _.matches方法匹配相同的元素,相同返回true,不同返回false

参数

  1. array (Array): 需要查询的数组
  2. [predicate=_.identity] (Function|Object|string): 遍历数组条件
  3. [thisArg] (*): The this binding of predicate.

返回值

(number): 返回匹配数组元素的索引值, 否则返回 -1.

例子

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

_.findLastIndex(users, function(chr) {
  return chr.user == 'pebbles';
});
// => 2

// using the `_.matches` callback shorthand
_.findLastIndex(users, { 'user': 'barney', 'active': true });
// => 0

// using the `_.matchesProperty` callback shorthand
_.findLastIndex(users, 'active', false);
// => 2

// using the `_.property` callback shorthand
_.findLastIndex(users, 'active');
// => 0

_.first(array)

#

获取数组 array的第一个元素

别名(Aliases)

_.head

参数

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

返回值

(*): 返回数组的第一个元素

例子

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

_.first([]);
// => undefined

_.flatten(array, [isDeep])

#

可以理解为将嵌套数组的维数减少,flattened(平坦). 如果 isDeep 值为 true 时,嵌套数组将递归为一维数组, 否则只减少嵌套数组一个级别的维数.

参数

  1. array (Array): 需要flattened(减少维数)的嵌套数组
  2. [isDeep] (boolean): 是否深递归

返回值

(Array): 返回处理后的数组

例子

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

// using `isDeep`
_.flatten([1, [2, 3, [4]]], true);
// => [1, 2, 3, 4]

_.flattenDeep(array)

#

递归地平坦一个嵌套的数组.相当于_.flatten(array, true)

参数

  1. array (Array): 需要

返回值

(Array): 返回处理后的数组.

例子

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

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

#

获取value在数组 array所在的索引值 使用 SameValueZero 来保证比较的质量(第一个全等===的元素). 如果 fromIndex 值是负数, 则从array末尾起算. 如果 fromIndex为true时,对已排序的数组array执行二分(二进制)查找

参数

  1. array (Array): 需要查找的数组
  2. value (*): 需要查找的元素
  3. [fromIndex=0] (boolean|number): 查询的位置或者true值时对一个已排序的数组进行二分查找.

返回值

(number): 返回元素在数组中的索引位置, else -1.

例子

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

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

// performing a binary search
_.indexOf([1, 1, 2, 2], 2, true);
// => 2

_.initial(array)

#

去除数组最后一个元素array.

参数

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

返回值

(Array): 返回截取的数组array.

例子

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

_.intersection([arrays])

#

取出各数组中全等的元素,使用 SameValueZero方式平等比较

参数

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

返回值

(Array): 返回共有元素的数组.

例子

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

_.last(array)

#

取出数组的最后一个元素 array.

参数

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

返回值

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

例子

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

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

#

该方法类似 _.indexOf ,只不过_.lastIndexOf是从右向左遍历数组array.

参数

  1. array (Array): 查询的数组
  2. value (*):查询的元素.
  3. [fromIndex=array.length-1] (boolean|number): 查询的起始位置或者为 true 时对已排序的数组进行二分查找.

返回值

(number): 返回第一个匹配值的索引值, 查询不到则返回 -1.

例子

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

// using `fromIndex`
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 1

// performing a binary search
_.lastIndexOf([1, 1, 2, 2], 2, true);
// => 3

_.pull(array, [values])

#

移除数组array中所有和 values 相等的元素,使用 SameValueZero 进行全等比较

Note: 不像 _.without方法,此方法改变了数组 array(并不是原来的数组了).

参数

  1. array (Array): 修改的数组
  2. [values] (...*): 移除的元素

返回值

(Array): 返回数组 array.

例子

var array = [1, 2, 3, 1, 2, 3];

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

_.pullAt(array, [indexes])

#

移除指定索引的数组元素,并返回移除的元素,索引值明确给出或者是索引数组.

Note:_.at方法不同, 此方法改变了数组 array(改变后一个新数组了).

参数

  1. array (Array): 需要修改的数组
  2. [indexes] (...(number|number[]): 需要移除元素的索引, 数组的索引值或者索引数组.

返回值

(Array): 返回移除元素后的新数组;

例子

var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);

console.log(array);
// => [5, 15]

console.log(evens);
// => [10, 20]

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

#

移除数组 array 中满足 predicate 条件的所有元素 ,返回的是被移除元素数组.

如果参数 predicate提供的是一个属性,则使用 _.property方法来判断

如果提供了参数 thisArg ,则使用 _.matchesProperty方法来判断属性是否等于此value



如果 predicate参数是一个对象,则使用 _.matches方法来判断比较这个对象

Note: 和方法 _.filter不一样, 此方法彻底改变数组array.

参数

  1. array (Array): 需要修改的数组
  2. [predicate=_.identity] (Function|Object|string): 遍历判断的方法
  3. [thisArg] (*): 和参数predicate绑定

返回值

(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]

_.rest(array)

#

获取数组 array第一个元素除外的所有元素.

别名(Aliases)

_.tail

参数

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

返回值

(Array): 返回截取的 array.

例子

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

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

#

start位置到 end(但不包含end位置),截取 array数组

Note: 此方法是用来在IE9以下版本替代 Array#slice来支持节点列表,确保密集数组返回

参数

  1. array (Array): 需要截取的数组.
  2. [start=0] (number): 截取开始位置
  3. [end=array.length] (number): 结束位置(不包含)

返回值

(Array): 返回截取后的数组 array.


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

#

Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order. If an iteratee function is provided it's invoked for value and each element of array to compute their sort ranking. The iteratee is bound to thisArg and invoked with one argument; (value).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. array (Array): 需要检查的数组
  2. value (*): 插入的判断参数
  3. [iteratee=_.identity] (Function|Object|string): 遍历方法
  4. [thisArg] (*): iteratee的绑定值

返回值

(number): 返回value 应该插入数组array位置的索引值

例子

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

_.sortedIndex([4, 4, 5, 5], 5);
// => 2

var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };

// using an iteratee function
_.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
  return this.data[word];
}, dict);
// => 1

// using the `_.property` callback shorthand
_.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
// => 1

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

#

用法类似于 _.sortedIndex ,不同的是从右至左计算插入的位置

参数

  1. array (Array): 需要检查的数组
  2. value (*): 插入的判断参数
  3. [iteratee=_.identity] (Function|Object|string): 遍历方法
  4. [thisArg] (*): iteratee的绑定值

返回值

(number): 返回value 应该插入数组array位置的索引值

例子

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

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

#

从数组的起始位置开始,取n个元素;n默认是1

参数

  1. array (Array): 需要查询的数组
  2. [n=1] (number): 获取的元素个数

返回值

(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])

#

从数组右侧开始 取得 n 个元素;n默认为1

参数

  1. array (Array): 需要查询的数组
  2. [n=1] (number): 获取的元素个数

返回值

(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], [thisArg])

#

Creates a slice of array with elements taken from the end. Elements are taken until predicate returns falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. array (Array): The array to query.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Array): Returns the slice of array.

例子

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

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// => ['pebbles']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.takeRightWhile(users, 'active', false), 'user');
// => ['fred', 'pebbles']

// using the `_.property` callback shorthand
_.pluck(_.takeRightWhile(users, 'active'), 'user');
// => []

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

#

Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. array (Array): The array to query.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Array): Returns the slice of array.

例子

_.takeWhile([1, 2, 3], function(n) {
  return n < 3;
});
// => [1, 2]

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false},
  { 'user': 'pebbles', 'active': true }
];

// using the `_.matches` callback shorthand
_.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
// => ['barney']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.takeWhile(users, 'active', false), 'user');
// => ['barney', 'fred']

// using the `_.property` callback shorthand
_.pluck(_.takeWhile(users, 'active'), 'user');
// => []

_.union([arrays])

#

Creates an array of unique values, in order, from all of the provided arrays using SameValueZero for equality comparisons.

参数

  1. [arrays] (...Array): The arrays to inspect.

返回值

(Array): Returns the new array of combined values.

例子

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

_.uniq(array, [isSorted], [iteratee], [thisArg])

#

Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only the first occurence of each element is kept. Providing true for isSorted performs a faster search algorithm for sorted arrays. If an iteratee function is provided it's invoked for each element in the array to generate the criterion by which uniqueness is computed. The iteratee is bound to thisArg and invoked with three arguments: (value, index, array).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

别名(Aliases)

_.unique

参数

  1. array (Array): The array to inspect.
  2. [isSorted] (boolean): Specify the array is sorted.
  3. [iteratee] (Function|Object|string): The function invoked per iteration.
  4. [thisArg] (*): The this binding of iteratee.

返回值

(Array): Returns the new duplicate-value-free array.

例子

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

// using `isSorted`
_.uniq([1, 1, 2], true);
// => [1, 2]

// using an iteratee function
_.uniq([1, 2.5, 1.5, 2], function(n) {
  return this.floor(n);
}, Math);
// => [1, 2.5]

// using the `_.property` callback shorthand
_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]

_.unzip(array)

#

This method is like _.zip except that it accepts an array of grouped elements and creates an array regrouping the elements to their pre-zip configuration.

参数

  1. array (Array): The array of grouped elements to process.

返回值

(Array): Returns the new array of regrouped elements.

例子

var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]

_.unzip(zipped);
// => [['fred', 'barney'], [30, 40], [true, false]]

_.unzipWith(array, [iteratee], [thisArg])

#

This method is like _.unzip except that it accepts an iteratee to specify how regrouped values should be combined. The iteratee is bound to thisArg and invoked with four arguments: (accumulator, value, index, group).

参数

  1. array (Array): The array of grouped elements to process.
  2. [iteratee] (Function): The function to combine regrouped values.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array): Returns the new array of regrouped elements.

例子

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

_.unzipWith(zipped, _.add);
// => [3, 30, 300]

_.without(array, [values])

#

Creates an array excluding all provided values using SameValueZero for equality comparisons.

参数

  1. array (Array): The array to filter.
  2. [values] (...*): The values to exclude.

返回值

(Array): Returns the new array of filtered values.

例子

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

_.xor([arrays])

#

Creates an array of unique values that is the symmetric difference of the provided arrays.

参数

  1. [arrays] (...Array): The arrays to inspect.

返回值

(Array): Returns the new array of values.

例子

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

_.zip([arrays])

#

Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

参数

  1. [arrays] (...Array): The arrays to process.

返回值

(Array): Returns the new array of grouped elements.

例子

_.zip(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]

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

#

The inverse of _.pairs; this method returns an object composed from arrays of property names and values. Provide either a single two dimensional array, e.g. [[key1, value1], [key2, value2]] or two arrays, one of property names and one of corresponding values.

别名(Aliases)

_.object

参数

  1. props (Array): The property names.
  2. [values=[]] (Array): The property values.

返回值

(Object): Returns the new object.

例子

_.zipObject([['fred', 30], ['barney', 40]]);
// => { 'fred': 30, 'barney': 40 }

_.zipObject(['fred', 'barney'], [30, 40]);
// => { 'fred': 30, 'barney': 40 }

_.zipWith([arrays], [iteratee], [thisArg])

#

This method is like _.zip except that it accepts an iteratee to specify how grouped values should be combined. The iteratee is bound to thisArg and invoked with four arguments: (accumulator, value, index, group).

参数

  1. [arrays] (...Array): The arrays to process.
  2. [iteratee] (Function): The function to combine grouped values.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array): Returns the new array of grouped elements.

例子

_.zipWith([1, 2], [10, 20], [100, 200], _.add);
// => [111, 222]

“Chain” Methods

_(value)

#

Creates a lodash object which wraps value to enable implicit chaining. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primitive value will automatically end the chain returning the unwrapped value. Explicit chaining may be enabled using _.chain. The execution of chained methods is lazy, that is, execution is deferred until _#value is implicitly or explicitly called.

Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion is an optimization strategy which merge iteratee calls; this can help to avoid the creation of intermediate data structures and greatly reduce the number of iteratee executions.

Chaining is supported in custom builds as long as the _#value method is directly or indirectly included in the build.

In addition to lodash methods, wrappers have Array and String methods.

The wrapper Array methods are:
concat, join, pop, push, reverse, shift, slice, sort, splice, and unshift

The wrapper String methods are:
replace and split

The wrapper methods that support shortcut fusion are:
compact, drop, dropRight, dropRightWhile, dropWhile, filter, first, initial, last, map, pluck, reject, rest, reverse, slice, take, takeRight, takeRightWhile, takeWhile, toArray, and where

The chainable wrapper methods are:
after, ary, assign, at, before, bind, bindAll, bindKey, callback, chain, chunk, commit, compact, concat, constant, countBy, create, curry, debounce, defaults, defaultsDeep, defer, delay, difference, drop, dropRight, dropRightWhile, dropWhile, fill, filter, flatten, flattenDeep, flow, flowRight, forEach, forEachRight, forIn, forInRight, forOwn, forOwnRight, functions, groupBy, indexBy, initial, intersection, invert, invoke, keys, keysIn, map, mapKeys, mapValues, matches, matchesProperty, memoize, merge, method, methodOf, mixin, modArgs, negate, omit, once, pairs, partial, partialRight, partition, pick, plant, pluck, property, propertyOf, pull, pullAt, push, range, rearg, reject, remove, rest, restParam, reverse, set, shuffle, slice, sort, sortBy, sortByAll, sortByOrder, splice, spread, take, takeRight, takeRightWhile, takeWhile, tap, throttle, thru, times, toArray, toPlainObject, transform, union, uniq, unshift, unzip, unzipWith, values, valuesIn, where, without, wrap, xor, zip, zipObject, zipWith

The wrapper methods that are not chainable by default are:
add, attempt, camelCase, capitalize, ceil, clone, cloneDeep, deburr, endsWith, escape, escapeRegExp, every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, findWhere, first, floor, get, gt, gte, has, identity, includes, indexOf, inRange, isArguments, isArray, isBoolean, isDate, isElement, isEmpty, isEqual, isError, isFinite isFunction, isMatch, isNative, isNaN, isNull, isNumber, isObject, isPlainObject, isRegExp, isString, isUndefined, isTypedArray, join, kebabCase, last, lastIndexOf, lt, lte, max, min, noConflict, noop, now, pad, padLeft, padRight, parseInt, pop, random, reduce, reduceRight, repeat, result, round, runInContext, shift, size, snakeCase, some, sortedIndex, sortedLastIndex, startCase, startsWith, sum, template, trim, trimLeft, trimRight, trunc, unescape, uniqueId, value, and words

The wrapper method sample will return a wrapped value when n is provided, otherwise an unwrapped value is returned.

参数

  1. value (*): The value to wrap in a lodash instance.

返回值

(Object): Returns the new lodash wrapper instance.

例子

var wrapped = _([1, 2, 3]);

// returns an unwrapped value
wrapped.reduce(function(total, n) {
  return total + n;
});
// => 6

// returns a wrapped value
var squares = wrapped.map(function(n) {
  return n * n;
});

_.isArray(squares);
// => false

_.isArray(squares.value());
// => true

_.chain(value)

#

Creates a lodash object that wraps value with explicit method chaining enabled.

参数

  1. value (*): The value to wrap.

返回值

(Object): Returns the new lodash wrapper instance.

例子

var users = [
  { 'user': 'barney',  'age': 36 },
  { 'user': 'fred',    'age': 40 },
  { 'user': 'pebbles', 'age': 1 }
];

var youngest = _.chain(users)
  .sortBy('age')
  .map(function(chr) {
    return chr.user + ' is ' + chr.age;
  })
  .first()
  .value();
// => 'pebbles is 1'

_.tap(value, interceptor, [thisArg])

#

This method invokes interceptor and returns value. The interceptor is bound to thisArg and invoked with one argument; (value). The purpose of this method is to "tap into" a method chain in order to perform operations on intermediate results within the chain.

参数

  1. value (*): The value to provide to interceptor.
  2. interceptor (Function): The function to invoke.
  3. [thisArg] (*): The this binding of interceptor.

返回值

(*): Returns value.

例子

_([1, 2, 3])
 .tap(function(array) {
   array.pop();
 })
 .reverse()
 .value();
// => [2, 1]

_.thru(value, interceptor, [thisArg])

#

This method is like _.tap except that it returns the result of interceptor.

参数

  1. value (*): The value to provide to interceptor.
  2. interceptor (Function): The function to invoke.
  3. [thisArg] (*): The this binding of interceptor.

返回值

(*): Returns the result of interceptor.

例子

_('  abc  ')
 .chain()
 .trim()
 .thru(function(value) {
   return [value];
 })
 .value();
// => ['abc']

_.prototype.chain()

#

Enables explicit method chaining on the wrapper object.

返回值

(Object): Returns the new lodash wrapper instance.

例子

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

// without explicit chaining
_(users).first();
// => { 'user': 'barney', 'age': 36 }

// with explicit chaining
_(users).chain()
  .first()
  .pick('user')
  .value();
// => { 'user': 'barney' }

_.prototype.commit()

#

Executes the chained sequence and returns the wrapped result.

返回值

(Object): Returns the new lodash wrapper instance.

例子

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.concat([values])

#

Creates a new array joining a wrapped array with any additional arrays and/or values.

参数

  1. [values] (...*): The values to concatenate.

返回值

(Array): Returns the new concatenated array.

例子

var array = [1];
var wrapped = _(array).concat(2, [3], [[4]]);

console.log(wrapped.value());
// => [1, 2, 3, [4]]

console.log(array);
// => [1]

_.prototype.plant()

#

Creates a clone of the chained sequence planting value as the wrapped value.

返回值

(Object): Returns the new lodash wrapper instance.

例子

var array = [1, 2];
var wrapped = _(array).map(function(value) {
  return Math.pow(value, 2);
});

var other = [3, 4];
var otherWrapped = wrapped.plant(other);

otherWrapped.value();
// => [9, 16]

wrapped.value();
// => [1, 4]

_.prototype.reverse()

#

Reverses the wrapped array so the first element becomes the last, the second element becomes the second to last, and so on.

Note: This method mutates the wrapped array.

返回值

(Object): Returns the new reversed lodash wrapper instance.

例子

var array = [1, 2, 3];

_(array).reverse().value()
// => [3, 2, 1]

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

_.prototype.toString()

#

Produces the result of coercing the unwrapped value to a string.

返回值

(string): Returns the coerced string value.

例子

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

_.prototype.value()

#

Executes the chained sequence to extract the unwrapped value.

别名(Aliases)

.prototype.run, .prototype.toJSON, _.prototype.valueOf

返回值

(*): Returns the resolved unwrapped value.

例子

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

“Collection” Methods

_.at(collection, [props])

#

Creates an array of elements corresponding to the given keys, or indexes, of collection. Keys may be specified as individual arguments or as arrays of keys.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [props] (...(number|number[]|string|string[]): The property names or indexes of elements to pick, specified individually or in arrays.

返回值

(Array): Returns the new array of picked elements.

例子

_.at(['a', 'b', 'c'], [0, 2]);
// => ['a', 'c']

_.at(['barney', 'fred', 'pebbles'], 0, 2);
// => ['barney', 'pebbles']

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

#

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the number of times the key was returned by iteratee. The iteratee is bound to thisArg and invoked with three arguments:
(value, index|key, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns the composed aggregate object.

例子

_.countBy([4.3, 6.1, 6.4], function(n) {
  return Math.floor(n);
});
// => { '4': 1, '6': 2 }

_.countBy([4.3, 6.1, 6.4], function(n) {
  return this.floor(n);
}, Math);
// => { '4': 1, '6': 2 }

_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }

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

#

Checks if predicate returns truthy for all elements of collection. The predicate is bound to thisArg and invoked with three arguments:
(value, index|key, collection).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

别名(Aliases)

_.all

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(boolean): Returns true if all elements pass the predicate check, else false.

例子

_.every([true, 1, null, 'yes'], Boolean);
// => false

var users = [
  { 'user': 'barney', 'active': false },
  { 'user': 'fred',   'active': false }
];

// using the `_.matches` callback shorthand
_.every(users, { 'user': 'barney', 'active': false });
// => false

// using the `_.matchesProperty` callback shorthand
_.every(users, 'active', false);
// => true

// using the `_.property` callback shorthand
_.every(users, 'active');
// => false

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

#

Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

别名(Aliases)

_.select

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Array): Returns the new filtered array.

例子

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

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
// => ['barney']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.filter(users, 'active', false), 'user');
// => ['fred']

// using the `_.property` callback shorthand
_.pluck(_.filter(users, 'active'), 'user');
// => ['barney']

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

#

Iterates over elements of collection, returning the first element predicate returns truthy for. The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

别名(Aliases)

_.detect

参数

  1. collection (Array|Object|string): The collection to search.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(*): Returns the matched element, else undefined.

例子

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.result(_.find(users, function(chr) {
  return chr.age < 40;
}), 'user');
// => 'barney'

// using the `_.matches` callback shorthand
_.result(_.find(users, { 'age': 1, 'active': true }), 'user');
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
_.result(_.find(users, 'active', false), 'user');
// => 'fred'

// using the `_.property` callback shorthand
_.result(_.find(users, 'active'), 'user');
// => 'barney'

_.findLast(collection, [predicate=_.identity], [thisArg])

#

This method is like _.find except that it iterates over elements of collection from right to left.

参数

  1. collection (Array|Object|string): The collection to search.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(*): Returns the matched element, else undefined.

例子

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

_.findWhere(collection, source)

#

Performs a deep comparison between each element in collection and the source object, returning the first element that has equivalent property values.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties. For comparing a single own or inherited property value see _.matchesProperty.

参数

  1. collection (Array|Object|string): The collection to search.
  2. source (Object): The object of property values to match.

返回值

(*): Returns the matched element, else undefined.

例子

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
// => 'barney'

_.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
// => 'fred'

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

#

Iterates over elements of collection invoking iteratee for each element. The iteratee is bound to thisArg and invoked with three arguments:
(value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

Note: As with other "Collections" methods, objects with a "length" property are iterated like arrays. To avoid this behavior _.forIn or _.forOwn may be used for object iteration.

别名(Aliases)

_.each

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array|Object|string): Returns collection.

例子

_([1, 2]).forEach(function(n) {
  console.log(n);
}).value();
// => logs each value from left to right and returns the array

_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
  console.log(n, key);
});
// => logs each value-key pair and returns the object (iteration order is not guaranteed)

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

#

This method is like _.forEach except that it iterates over elements of collection from right to left.

别名(Aliases)

_.eachRight

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array|Object|string): Returns collection.

例子

_([1, 2]).forEachRight(function(n) {
  console.log(n);
}).value();
// => logs each value from right to left and returns the array

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

#

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is an array of the elements responsible for generating the key. The iteratee is bound to thisArg and invoked with three arguments:
(value, index|key, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns the composed aggregate object.

例子

_.groupBy([4.2, 6.1, 6.4], function(n) {
  return Math.floor(n);
});
// => { '4': [4.2], '6': [6.1, 6.4] }

_.groupBy([4.2, 6.1, 6.4], function(n) {
  return this.floor(n);
}, Math);
// => { '4': [4.2], '6': [6.1, 6.4] }

// using the `_.property` callback shorthand
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }

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

#

Checks if target is in collection using SameValueZero for equality comparisons. If fromIndex is negative, it's used as the offset from the end of collection.

别名(Aliases)

.contains, .include

参数

  1. collection (Array|Object|string): The collection to search.
  2. target (*): The value to search for.
  3. [fromIndex=0] (number): The index to search from.

返回值

(boolean): Returns true if a matching element is found, else false.

例子

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

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

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');
// => true

_.includes('pebbles', 'eb');
// => true

_.indexBy(collection, [iteratee=_.identity], [thisArg])

#

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the last element responsible for generating the key. The iteratee function is bound to thisArg and invoked with three arguments:
(value, index|key, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns the composed aggregate object.

例子

var keyData = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];

_.indexBy(keyData, 'dir');
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }

_.indexBy(keyData, function(object) {
  return String.fromCharCode(object.code);
});
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }

_.indexBy(keyData, function(object) {
  return this.fromCharCode(object.code);
}, String);
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }

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

#

Invokes the method at path of each element in collection, returning an array of the results of each invoked method. Any additional arguments are provided to each invoked method. If methodName is a function it's invoked for, and this bound to, each element in collection.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. path (Array|Function|string): The path of the method to invoke or the function invoked per iteration.
  3. [args] (...*): The arguments to invoke the method with.

返回值

(Array): Returns the array of results.

例子

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]]

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

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

#

Creates an array of values by running each element in collection through iteratee. The iteratee is bound to thisArg and invoked with three arguments: (value, index|key, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

Many lodash methods are guarded to work as iteratees for methods like _.every, _.filter, _.map, _.mapValues, _.reject, and _.some.

The guarded methods are:
ary, callback, chunk, clone, create, curry, curryRight, drop, dropRight, every, fill, flatten, invert, max, min, parseInt, slice, sortBy, take, takeRight, template, trim, trimLeft, trimRight, trunc, random, range, sample, some, sum, uniq, and words

别名(Aliases)

_.collect

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array): Returns the new mapped array.

例子

function timesThree(n) {
  return n * 3;
}

_.map([1, 2], timesThree);
// => [3, 6]

_.map({ 'a': 1, 'b': 2 }, timesThree);
// => [3, 6] (iteration order is not guaranteed)

var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];

// using the `_.property` callback shorthand
_.map(users, 'user');
// => ['barney', 'fred']

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

#

Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, while the second of which contains elements predicate returns falsey for. The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Array): Returns the array of grouped elements.

例子

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

_.partition([1.2, 2.3, 3.4], function(n) {
  return this.floor(n) % 2;
}, Math);
// => [[1.2, 3.4], [2.3]]

var users = [
  { 'user': 'barney',  'age': 36, 'active': false },
  { 'user': 'fred',    'age': 40, 'active': true },
  { 'user': 'pebbles', 'age': 1,  'active': false }
];

var mapper = function(array) {
  return _.pluck(array, 'user');
};

// using the `_.matches` callback shorthand
_.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
// => [['pebbles'], ['barney', 'fred']]

// using the `_.matchesProperty` callback shorthand
_.map(_.partition(users, 'active', false), mapper);
// => [['barney', 'pebbles'], ['fred']]

// using the `_.property` callback shorthand
_.map(_.partition(users, 'active'), mapper);
// => [['fred'], ['barney', 'pebbles']]

_.pluck(collection, path)

#

Gets the property value of path from all elements in collection.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. path (Array|string): The path of the property to pluck.

返回值

(Array): Returns the property values.

例子

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

_.pluck(users, 'user');
// => ['barney', 'fred']

var userIndex = _.indexBy(users, 'user');
_.pluck(userIndex, 'age');
// => [36, 40] (iteration order is not guaranteed)

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

#

Reduces collection to a value which is the accumulated result of running each element in collection through iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not provided the first element of collection is used as the initial value. The iteratee is bound to thisArg and invoked with four arguments:
(accumulator, value, index|key, collection).

Many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform.

The guarded methods are:
assign, defaults, defaultsDeep, includes, merge, sortByAll, and sortByOrder

别名(Aliases)

.foldl, .inject

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [accumulator] (*): The initial value.
  4. [thisArg] (*): The this binding of iteratee.

返回值

(*): Returns the accumulated value.

例子

_.reduce([1, 2], function(total, n) {
  return total + n;
});
// => 3

_.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
  result[key] = n * 3;
  return result;
}, {});
// => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)

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

#

This method is like _.reduce except that it iterates over elements of collection from right to left.

别名(Aliases)

_.foldr

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [accumulator] (*): The initial value.
  4. [thisArg] (*): The this binding of iteratee.

返回值

(*): Returns the accumulated value.

例子

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], [thisArg])

#

The opposite of _.filter; this method returns the elements of collection that predicate does not return truthy for.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Array): Returns the new filtered array.

例子

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

var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': true }
];

// using the `_.matches` callback shorthand
_.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
// => ['barney']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.reject(users, 'active', false), 'user');
// => ['fred']

// using the `_.property` callback shorthand
_.pluck(_.reject(users, 'active'), 'user');
// => ['barney']

_.sample(collection, [n])

#

Gets a random element or n random elements from a collection.

参数

  1. collection (Array|Object|string): The collection to sample.
  2. [n] (number): The number of elements to sample.

返回值

(*): Returns the random sample(s).

例子

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

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

_.shuffle(collection)

#

Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.

参数

  1. collection (Array|Object|string): The collection to shuffle.

返回值

(Array): Returns the new shuffled array.

例子

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

_.size(collection)

#

Gets the size of collection by returning its length for array-like values or the number of own enumerable properties for objects.

参数

  1. collection (Array|Object|string): The collection to inspect.

返回值

(number): Returns the size of collection.

例子

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

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

_.size('pebbles');
// => 7

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

#

Checks if predicate returns truthy for any element of collection. The function returns as soon as it finds a passing value and does not iterate over the entire collection. The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

别名(Aliases)

_.any

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(boolean): Returns true if any element passes the predicate check, else false.

例子

_.some([null, 0, 'yes', false], Boolean);
// => true

var users = [
  { 'user': 'barney', 'active': true },
  { 'user': 'fred',   'active': false }
];

// using the `_.matches` callback shorthand
_.some(users, { 'user': 'barney', 'active': false });
// => false

// using the `_.matchesProperty` callback shorthand
_.some(users, 'active', false);
// => true

// using the `_.property` callback shorthand
_.some(users, 'active');
// => true

_.sortBy(collection, [iteratee=_.identity], [thisArg])

#

Creates an array of elements, sorted in ascending order by the results of running each element in a collection through iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratee is bound to thisArg and invoked with three arguments:
(value, index|key, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array): Returns the new sorted array.

例子

_.sortBy([1, 2, 3], function(n) {
  return Math.sin(n);
});
// => [3, 1, 2]

_.sortBy([1, 2, 3], function(n) {
  return this.sin(n);
}, Math);
// => [3, 1, 2]

var users = [
  { 'user': 'fred' },
  { 'user': 'pebbles' },
  { 'user': 'barney' }
];

// using the `_.property` callback shorthand
_.pluck(_.sortBy(users, 'user'), 'user');
// => ['barney', 'fred', 'pebbles']

_.sortByAll(collection, iteratees)

#

This method is like _.sortBy except that it can sort by multiple iteratees or property names.

If a property name is provided for an iteratee the created _.property style callback returns the property value of the given element.

If an object is provided for an iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. iteratees (...(Function|Function[]|Object|Object[]|string|string[]): The iteratees to sort by, specified as individual values or arrays of values.

返回值

(Array): Returns the new sorted array.

例子

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 42 },
  { 'user': 'barney', 'age': 34 }
];

_.map(_.sortByAll(users, ['user', 'age']), _.values);
// => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]

_.map(_.sortByAll(users, 'user', function(chr) {
  return Math.floor(chr.age / 10);
}), _.values);
// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]

_.sortByOrder(collection, iteratees, [orders])

#

This method is like _.sortByAll except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, a value is sorted in ascending order if its corresponding order is "asc", and descending if "desc".

If a property name is provided for an iteratee the created _.property style callback returns the property value of the given element.

If an object is provided for an iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. iteratees (Function[]|Object[]|string[]): The iteratees to sort by.
  3. [orders] (boolean[]): The sort orders of iteratees.

返回值

(Array): Returns the new sorted array.

例子

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 34 },
  { 'user': 'fred',   'age': 42 },
  { 'user': 'barney', 'age': 36 }
];

// sort by `user` in ascending order and by `age` in descending order
_.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]

_.where(collection, source)

#

Performs a deep comparison between each element in collection and the source object, returning an array of all elements that have equivalent property values.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties. For comparing a single own or inherited property value see _.matchesProperty.

参数

  1. collection (Array|Object|string): The collection to search.
  2. source (Object): The object of property values to match.

返回值

(Array): Returns the new filtered array.

例子

var users = [
  { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
  { 'user': 'fred',   'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
];

_.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
// => ['barney']

_.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
// => ['fred']

“Date” Methods

_.now

#

Gets the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).

例子

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

“Function” Methods

_.after(n, func)

#

The opposite of _.before; this method creates a function that invokes func once it's called n or more times.

参数

  1. n (number): The number of calls before func is invoked.
  2. func (Function): The function to restrict.

返回值

(Function): Returns the new restricted 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])

#

Creates a function that accepts up to n arguments ignoring any additional arguments.

参数

  1. func (Function): The function to cap arguments for.
  2. [n=func.length] (number): The arity cap.

返回值

(Function): Returns the new function.

例子

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

_.before(n, func)

#

Creates a function that invokes func, with the this binding and arguments of the created function, while it's called less than n times. Subsequent calls to the created function return the result of the last func invocation.

参数

  1. n (number): The number of calls at which func is no longer invoked.
  2. func (Function): The function to restrict.

返回值

(Function): Returns the new restricted function.

例子

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

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

#

Creates a function that invokes func with the this binding of thisArg and prepends any additional _.bind arguments to those provided to the bound function.

The _.bind.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Note: Unlike native Function#bind this method does not set the "length" property of bound functions.

参数

  1. func (Function): The function to bind.
  2. thisArg (*): The this binding of func.
  3. [partials] (...*): The arguments to be partially applied.

返回值

(Function): Returns the new bound function.

例子

var greet = function(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
};

var object = { 'user': 'fred' };

var bound = _.bind(greet, object, 'hi');
bound('!');
// => 'hi fred!'

// using placeholders
var bound = _.bind(greet, object, _, '!');
bound('hi');
// => 'hi fred!'

_.bindAll(object, [methodNames])

#

Binds methods of an object to the object itself, overwriting the existing method. Method names may be specified as individual arguments or as arrays of method names. If no method names are provided all enumerable function properties, own and inherited, of object are bound.

Note: This method does not set the "length" property of bound functions.

参数

  1. object (Object): The object to bind and assign the bound methods to.
  2. [methodNames] (...(string|string[]): The object method names to bind, specified as individual method names or arrays of method names.

返回值

(Object): Returns object.

例子

var view = {
  'label': 'docs',
  'onClick': function() {
    console.log('clicked ' + this.label);
  }
};

_.bindAll(view);
jQuery('#docs').on('click', view.onClick);
// => logs 'clicked docs' when the element is clicked

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

#

Creates a function that invokes the method at object[key] and prepends any additional _.bindKey arguments to those provided to the bound function.

This method differs from _.bind by allowing bound functions to reference methods that may be redefined or don't yet exist. See Peter Michaux's article for more details.

The _.bindKey.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

参数

  1. object (Object): The object the method belongs to.
  2. key (string): The key of the method.
  3. [partials] (...*): The arguments to be partially applied.

返回值

(Function): Returns the new bound function.

例子

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!'

// using placeholders
var bound = _.bindKey(object, 'greet', _, '!');
bound('hi');
// => 'hiya fred!'

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

#

Creates a function that accepts one or more arguments of func that when called either invokes func returning its result, if all func arguments have been provided, or returns a function that accepts one or more of the remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient.

The _.curry.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for provided arguments.

Note: This method does not set the "length" property of curried functions.

参数

  1. func (Function): The function to curry.
  2. [arity=func.length] (number): The arity of func.

返回值

(Function): Returns the new curried function.

例子

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]

// using placeholders
curried(1)(_, 3)(2);
// => [1, 2, 3]

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

#

This method is like _.curry except that arguments are applied to func in the manner of _.partialRight instead of _.partial.

The _.curryRight.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for provided arguments.

Note: This method does not set the "length" property of curried functions.

参数

  1. func (Function): The function to curry.
  2. [arity=func.length] (number): The arity of func.

返回值

(Function): Returns the new curried function.

例子

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]

// using placeholders
curried(3)(1, _)(2);
// => [1, 2, 3]

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

#

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the result of the last func invocation.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the the debounced function is invoked more than once during the wait timeout.

See David Corbacho's article for details over the differences between _.debounce and _.throttle.

参数

  1. func (Function): The function to debounce.
  2. [wait=0] (number): The number of milliseconds to delay.
  3. [options] (Object): The options object.
  4. [options.leading=false] (boolean): Specify invoking on the leading edge of the timeout.
  5. [options.maxWait] (number): The maximum time func is allowed to be delayed before it's invoked.
  6. [options.trailing=true] (boolean): Specify invoking on the trailing edge of the timeout.

返回值

(Function): Returns the new debounced function.

例子

// avoid costly calculations while the window size is in flux
jQuery(window).on('resize', _.debounce(calculateLayout, 150));

// invoke `sendMail` when the click event is fired, debouncing subsequent calls
jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));

// ensure `batchLog` is invoked once after 1 second of debounced calls
var source = new EventSource('/stream');
jQuery(source).on('message', _.debounce(batchLog, 250, {
  'maxWait': 1000
}));

// cancel a debounced call
var todoChanges = _.debounce(batchLog, 1000);
Object.observe(models.todo, todoChanges);

Object.observe(models, function(changes) {
  if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
    todoChanges.cancel();
  }
}, ['delete']);

// ...at some point `models.todo` is changed
models.todo.completed = true;

// ...before 1 second has passed `models.todo` is deleted
// which cancels the debounced `todoChanges` call
delete models.todo;

_.defer(func, [args])

#

Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to func when it's invoked.

参数

  1. func (Function): The function to defer.
  2. [args] (...*): The arguments to invoke the function with.

返回值

(number): Returns the timer id.

例子

_.defer(function(text) {
  console.log(text);
}, 'deferred');
// logs 'deferred' after one or more milliseconds

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

#

Invokes func after wait milliseconds. Any additional arguments are provided to func when it's invoked.

参数

  1. func (Function): The function to delay.
  2. wait (number): The number of milliseconds to delay invocation.
  3. [args] (...*): The arguments to invoke the function with.

返回值

(number): Returns the timer id.

例子

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

_.flow([funcs])

#

Creates a function that returns the result of invoking the provided functions with the this binding of the created function, where each successive invocation is supplied the return value of the previous.

参数

  1. [funcs] (...Function): Functions to invoke.

返回值

(Function): Returns the new function.

例子

function square(n) {
  return n * n;
}

var addSquare = _.flow(_.add, square);
addSquare(1, 2);
// => 9

_.flowRight([funcs])

#

This method is like _.flow except that it creates a function that invokes the provided functions from right to left.

别名(Aliases)

.backflow, .compose

参数

  1. [funcs] (...Function): Functions to invoke.

返回值

(Function): Returns the new function.

例子

function square(n) {
  return n * n;
}

var addSquare = _.flowRight(square, _.add);
addSquare(1, 2);
// => 9

_.memoize(func, [resolver])

#

Creates a function that memoizes the result of func. If resolver is provided it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is coerced to a string and used as the cache key. The func is invoked with the this binding of the memoized function.

Note: The cache is exposed as the cache property on the memoized function. Its creation may be customized by replacing the _.memoize.Cache constructor with one whose instances implement the Map method interface of get, has, and set.

参数

  1. func (Function): The function to have its output memoized.
  2. [resolver] (Function): The function to resolve the cache key.

返回值

(Function): Returns the new memoizing function.

例子

var upperCase = _.memoize(function(string) {
  return string.toUpperCase();
});

upperCase('fred');
// => 'FRED'

// modifying the result cache
upperCase.cache.set('fred', 'BARNEY');
upperCase('fred');
// => 'BARNEY'

// replacing `_.memoize.Cache`
var object = { 'user': 'fred' };
var other = { 'user': 'barney' };
var identity = _.memoize(_.identity);

identity(object);
// => { 'user': 'fred' }
identity(other);
// => { 'user': 'fred' }

_.memoize.Cache = WeakMap;
var identity = _.memoize(_.identity);

identity(object);
// => { 'user': 'fred' }
identity(other);
// => { 'user': 'barney' }

_.modArgs(func, [transforms])

#

Creates a function that runs each argument through a corresponding transform function.

参数

  1. func (Function): The function to wrap.
  2. [transforms] (...(Function|Function[]): The functions to transform arguments, specified as individual functions or arrays of functions.

返回值

(Function): Returns the new function.

例子

function doubled(n) {
  return n * 2;
}

function square(n) {
  return n * n;
}

var modded = _.modArgs(function(x, y) {
  return [x, y];
}, square, doubled);

modded(1, 2);
// => [1, 4]

modded(5, 10);
// => [25, 20]

_.negate(predicate)

#

Creates a function that negates the result of the predicate func. The func predicate is invoked with the this binding and arguments of the created function.

参数

  1. predicate (Function): The predicate to negate.

返回值

(Function): Returns the new function.

例子

function isEven(n) {
  return n % 2 == 0;
}

_.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
// => [1, 3, 5]

_.once(func)

#

Creates a function that is restricted to invoking func once. Repeat calls to the function return the value of the first call. The func is invoked with the this binding and arguments of the created function.

参数

  1. func (Function): The function to restrict.

返回值

(Function): Returns the new restricted function.

例子

var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` invokes `createApplication` once

_.partial(func, [partials])

#

Creates a function that invokes func with partial arguments prepended to those provided to the new function. This method is like _.bind except it does not alter the this binding.

The _.partial.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Note: This method does not set the "length" property of partially applied functions.

参数

  1. func (Function): The function to partially apply arguments to.
  2. [partials] (...*): The arguments to be partially applied.

返回值

(Function): Returns the new partially applied function.

例子

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// => 'hello fred'

// using placeholders
var greetFred = _.partial(greet, _, 'fred');
greetFred('hi');
// => 'hi fred'

_.partialRight(func, [partials])

#

This method is like _.partial except that partially applied arguments are appended to those provided to the new function.

The _.partialRight.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Note: This method does not set the "length" property of partially applied functions.

参数

  1. func (Function): The function to partially apply arguments to.
  2. [partials] (...*): The arguments to be partially applied.

返回值

(Function): Returns the new partially applied function.

例子

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var greetFred = _.partialRight(greet, 'fred');
greetFred('hi');
// => 'hi fred'

// using placeholders
var sayHelloTo = _.partialRight(greet, 'hello', _);
sayHelloTo('fred');
// => 'hello fred'

_.rearg(func, indexes)

#

Creates a function that invokes func with arguments arranged according to the specified indexes where the argument value at the first index is provided as the first argument, the argument value at the second index is provided as the second argument, and so on.

参数

  1. func (Function): The function to rearrange arguments for.
  2. indexes (...(number|number[]): The arranged argument indexes, specified as individual indexes or arrays of indexes.

返回值

(Function): Returns the new function.

例子

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

rearged('b', 'c', 'a')
// => ['a', 'b', 'c']

var map = _.rearg(_.map, [1, 0]);
map(function(n) {
  return n * 3;
}, [1, 2, 3]);
// => [3, 6, 9]

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

#

Creates a function that invokes func with the this binding of the created function and arguments from start and beyond provided as an array.

Note: This method is based on the rest parameter.

参数

  1. func (Function): The function to apply a rest parameter to.
  2. [start=func.length-1] (number): The start position of the rest parameter.

返回值

(Function): Returns the new function.

例子

var say = _.restParam(function(what, names) {
  return what + ' ' + _.initial(names).join(', ') +
    (_.size(names) > 1 ? ', & ' : '') + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// => 'hello fred, barney, & pebbles'

_.spread(func)

#

Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply.

Note: This method is based on the spread operator.

参数

  1. func (Function): The function to spread arguments over.

返回值

(Function): Returns the new function.

例子

var say = _.spread(function(who, what) {
  return who + ' says ' + what;
});

say(['fred', 'hello']);
// => 'fred says hello'

// with a Promise
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])

#

Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled function return the result of the last func call.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the the throttled function is invoked more than once during the wait timeout.

See David Corbacho's article for details over the differences between _.throttle and _.debounce.

参数

  1. func (Function): The function to throttle.
  2. [wait=0] (number): The number of milliseconds to throttle invocations to.
  3. [options] (Object): The options object.
  4. [options.leading=true] (boolean): Specify invoking on the leading edge of the timeout.
  5. [options.trailing=true] (boolean): Specify invoking on the trailing edge of the timeout.

返回值

(Function): Returns the new throttled function.

例子

// 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
jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  'trailing': false
}));

// cancel a trailing throttled call
jQuery(window).on('popstate', throttled.cancel);

_.wrap(value, wrapper)

#

Creates a function that provides value to the wrapper function as its first argument. Any additional arguments provided to the function are appended to those provided to the wrapper function. The wrapper is invoked with the this binding of the created function.

参数

  1. value (*): The value to wrap.
  2. wrapper (Function): The wrapper function.

返回值

(Function): Returns the new function.

例子

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

p('fred, barney, & pebbles');
// => '<p>fred, barney, &amp; pebbles</p>'

“Lang” Methods

_.clone(value, [isDeep], [customizer], [thisArg])

#

Creates a clone of value. If isDeep is true nested objects are cloned, otherwise they are assigned by reference. If customizer is provided it's invoked to produce the cloned values. If customizer returns undefined cloning is handled by the method instead. The customizer is bound to thisArg and invoked with up to three argument; (value [, index|key, object]).

Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments objects and objects created by constructors other than Object are cloned to plain Object objects. An empty object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps.

参数

  1. value (*): The value to clone.
  2. [isDeep] (boolean): Specify a deep clone.
  3. [customizer] (Function): The function to customize cloning values.
  4. [thisArg] (*): The this binding of customizer.

返回值

(*): Returns the cloned value.

例子

var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];

var shallow = _.clone(users);
shallow[0] === users[0];
// => true

var deep = _.clone(users, true);
deep[0] === users[0];
// => false

// using a customizer callback
var el = _.clone(document.body, function(value) {
  if (_.isElement(value)) {
    return value.cloneNode(false);
  }
});

el === document.body
// => false
el.nodeName
// => BODY
el.childNodes.length;
// => 0

_.cloneDeep(value, [customizer], [thisArg])

#

Creates a deep clone of value. If customizer is provided it's invoked to produce the cloned values. If customizer returns undefined cloning is handled by the method instead. The customizer is bound to thisArg and invoked with up to three argument; (value [, index|key, object]).

Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments objects and objects created by constructors other than Object are cloned to plain Object objects. An empty object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps.

参数

  1. value (*): The value to deep clone.
  2. [customizer] (Function): The function to customize cloning values.
  3. [thisArg] (*): The this binding of customizer.

返回值

(*): Returns the deep cloned value.

例子

var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];

var deep = _.cloneDeep(users);
deep[0] === users[0];
// => false

// using a customizer callback
var el = _.cloneDeep(document.body, function(value) {
  if (_.isElement(value)) {
    return value.cloneNode(true);
  }
});

el === document.body
// => false
el.nodeName
// => BODY
el.childNodes.length;
// => 20

_.gt(value, other)

#

Checks if value is greater than other.

参数

  1. value (*): The value to compare.
  2. other (*): The other value to compare.

返回值

(boolean): Returns true if value is greater than other, else false.

例子

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

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

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

_.gte(value, other)

#

Checks if value is greater than or equal to other.

参数

  1. value (*): The value to compare.
  2. other (*): The other value to compare.

返回值

(boolean): Returns true if value is greater than or equal to other, else false.

例子

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

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

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

_.isArguments(value)

#

Checks if value is classified as an arguments object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

_.isArguments(function() { return arguments; }());
// => true

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

_.isArray(value)

#

Checks if value is classified as an Array object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

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

_.isArray(function() { return arguments; }());
// => false

_.isBoolean(value)

#

Checks if value is classified as a boolean primitive or object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

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

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

_.isDate(value)

#

Checks if value is classified as a Date object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

_.isDate(new Date);
// => true

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

_.isElement(value)

#

Checks if value is a DOM element.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is a DOM element, else false.

例子

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

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

_.isEmpty(value)

#

Checks if value is empty. A value is considered empty unless it's an arguments object, array, string, or jQuery-like collection with a length greater than 0 or an object with own enumerable properties.

参数

  1. value (Array|Object|string): The value to inspect.

返回值

(boolean): Returns true if value is empty, else false.

例子

_.isEmpty(null);
// => true

_.isEmpty(true);
// => true

_.isEmpty(1);
// => true

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

_.isEmpty({ 'a': 1 });
// => false

_.isEqual(value, other, [customizer], [thisArg])

#

Performs a deep comparison between two values to determine if they are equivalent. If customizer is provided it's invoked to compare values. If customizer returns undefined comparisons are handled by the method instead. The customizer is bound to thisArg and invoked with up to three arguments: (value, other [, index|key]).

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties. Functions and DOM nodes are not supported. Provide a customizer function to extend support for comparing other values.

别名(Aliases)

_.eq

参数

  1. value (*): The value to compare.
  2. other (*): The other value to compare.
  3. [customizer] (Function): The function to customize value comparisons.
  4. [thisArg] (*): The this binding of customizer.

返回值

(boolean): Returns true if the values are equivalent, else false.

例子

var object = { 'user': 'fred' };
var other = { 'user': 'fred' };

object == other;
// => false

_.isEqual(object, other);
// => true

// using a customizer callback
var array = ['hello', 'goodbye'];
var other = ['hi', 'goodbye'];

_.isEqual(array, other, function(value, other) {
  if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
    return true;
  }
});
// => true

_.isError(value)

#

Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is an error object, else false.

例子

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

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

_.isFinite(value)

#

Checks if value is a finite primitive number.

Note: This method is based on Number.isFinite.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is a finite number, else false.

例子

_.isFinite(10);
// => true

_.isFinite('10');
// => false

_.isFinite(true);
// => false

_.isFinite(Object(10));
// => false

_.isFinite(Infinity);
// => false

_.isFunction(value)

#

Checks if value is classified as a Function object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

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

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

_.isMatch(object, source, [customizer], [thisArg])

#

Performs a deep comparison between object and source to determine if object contains equivalent property values. If customizer is provided it's invoked to compare values. If customizer returns undefined comparisons are handled by the method instead. The customizer is bound to thisArg and invoked with three arguments: (value, other, index|key).

Note: This method supports comparing properties of arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Functions and DOM nodes are not supported. Provide a customizer function to extend support for comparing other values.

参数

  1. object (Object): The object to inspect.
  2. source (Object): The object of property values to match.
  3. [customizer] (Function): The function to customize value comparisons.
  4. [thisArg] (*): The this binding of customizer.

返回值

(boolean): Returns true if object is a match, else false.

例子

var object = { 'user': 'fred', 'age': 40 };

_.isMatch(object, { 'age': 40 });
// => true

_.isMatch(object, { 'age': 36 });
// => false

// using a customizer callback
var object = { 'greeting': 'hello' };
var source = { 'greeting': 'hi' };

_.isMatch(object, source, function(value, other) {
  return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
});
// => true

_.isNaN(value)

#

Checks if value is NaN.

Note: This method is not the same as isNaN which returns true for undefined and other non-numeric values.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is NaN, else false.

例子

_.isNaN(NaN);
// => true

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

isNaN(undefined);
// => true

_.isNaN(undefined);
// => false

_.isNative(value)

#

Checks if value is a native function.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is a native function, else false.

例子

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

_.isNative(_);
// => false

_.isNull(value)

#

Checks if value is null.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is null, else false.

例子

_.isNull(null);
// => true

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

_.isNumber(value)

#

Checks if value is classified as a Number primitive or object.

Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

_.isNumber(8.4);
// => true

_.isNumber(NaN);
// => true

_.isNumber('8.4');
// => false

_.isObject(value)

#

Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is an object, else false.

例子

_.isObject({});
// => true

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

_.isObject(1);
// => false

_.isPlainObject(value)

#

Checks if value is a plain object, that is, an object created by the Object constructor or one with a [[Prototype]] of null.

Note: This method assumes objects created by the Object constructor have no inherited enumerable properties.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is a plain object, else 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)

#

Checks if value is classified as a RegExp object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

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

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

_.isString(value)

#

Checks if value is classified as a String primitive or object.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

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

_.isString(1);
// => false

_.isTypedArray(value)

#

Checks if value is classified as a typed array.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is correctly classified, else false.

例子

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

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

_.isUndefined(value)

#

Checks if value is undefined.

参数

  1. value (*): The value to check.

返回值

(boolean): Returns true if value is undefined, else false.

例子

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

_.isUndefined(null);
// => false

_.lt(value, other)

#

Checks if value is less than other.

参数

  1. value (*): The value to compare.
  2. other (*): The other value to compare.

返回值

(boolean): Returns true if value is less than other, else false.

例子

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

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

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

_.lte(value, other)

#

Checks if value is less than or equal to other.

参数

  1. value (*): The value to compare.
  2. other (*): The other value to compare.

返回值

(boolean): Returns true if value is less than or equal to other, else false.

例子

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

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

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

_.toArray(value)

#

Converts value to an array.

参数

  1. value (*): The value to convert.

返回值

(Array): Returns the converted array.

例子

(function() {
  return _.toArray(arguments).slice(1);
}(1, 2, 3));
// => [2, 3]

_.toPlainObject(value)

#

Converts value to a plain object flattening inherited enumerable properties of value to own properties of the plain object.

参数

  1. value (*): The value to convert.

返回值

(Object): Returns the converted plain 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 }

“Math” Methods

_.add(augend, addend)

#

Adds two numbers.

参数

  1. augend (number): The first number to add.
  2. addend (number): The second number to add.

返回值

(number): Returns the sum.

例子

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

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

#

Calculates n rounded up to precision.

参数

  1. n (number): The number to round up.
  2. [precision=0] (number): The precision to round up to.

返回值

(number): Returns the rounded up number.

例子

_.ceil(4.006);
// => 5

_.ceil(6.004, 2);
// => 6.01

_.ceil(6040, -2);
// => 6100

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

#

Calculates n rounded down to precision.

参数

  1. n (number): The number to round down.
  2. [precision=0] (number): The precision to round down to.

返回值

(number): Returns the rounded down number.

例子

_.floor(4.006);
// => 4

_.floor(0.046, 2);
// => 0.04

_.floor(4060, -2);
// => 4000

_.max(collection, [iteratee], [thisArg])

#

Gets the maximum value of collection. If collection is empty or falsey -Infinity is returned. If an iteratee function is provided it's invoked for each value in collection to generate the criterion by which the value is ranked. The iteratee is bound to thisArg and invoked with three arguments: (value, index, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(*): Returns the maximum value.

例子

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

_.max([]);
// => -Infinity

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

_.max(users, function(chr) {
  return chr.age;
});
// => { 'user': 'fred', 'age': 40 }

// using the `_.property` callback shorthand
_.max(users, 'age');
// => { 'user': 'fred', 'age': 40 }

_.min(collection, [iteratee], [thisArg])

#

Gets the minimum value of collection. If collection is empty or falsey Infinity is returned. If an iteratee function is provided it's invoked for each value in collection to generate the criterion by which the value is ranked. The iteratee is bound to thisArg and invoked with three arguments: (value, index, collection).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(*): Returns the minimum value.

例子

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

_.min([]);
// => Infinity

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

_.min(users, function(chr) {
  return chr.age;
});
// => { 'user': 'barney', 'age': 36 }

// using the `_.property` callback shorthand
_.min(users, 'age');
// => { 'user': 'barney', 'age': 36 }

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

#

Calculates n rounded to precision.

参数

  1. n (number): The number to round.
  2. [precision=0] (number): The precision to round to.

返回值

(number): Returns the rounded number.

例子

_.round(4.006);
// => 4

_.round(4.006, 2);
// => 4.01

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

_.sum(collection, [iteratee], [thisArg])

#

Gets the sum of the values in collection.

参数

  1. collection (Array|Object|string): The collection to iterate over.
  2. [iteratee] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(number): Returns the sum.

例子

_.sum([4, 6]);
// => 10

_.sum({ 'a': 4, 'b': 6 });
// => 10

var objects = [
  { 'n': 4 },
  { 'n': 6 }
];

_.sum(objects, function(object) {
  return object.n;
});
// => 10

// using the `_.property` callback shorthand
_.sum(objects, 'n');
// => 10

“Number” Methods

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

#

Checks if n is between start and up to but not including, end. If end is not specified it's set to start with start then set to 0.

参数

  1. n (number): The number to check.
  2. [start=0] (number): The start of the range.
  3. end (number): The end of the range.

返回值

(boolean): Returns true if n is in the range, else 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

_.random([min=0], [max=1], [floating])

#

Produces a random number between min and max (inclusive). If only one argument is provided a number between 0 and the given number is returned. If floating is true, or either min or max are floats, a floating-point number is returned instead of an integer.

参数

  1. [min=0] (number): The minimum possible value.
  2. [max=1] (number): The maximum possible value.
  3. [floating] (boolean): Specify returning a floating-point number.

返回值

(number): Returns the random number.

例子

_.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

“Object” Methods

_.assign(object, [sources], [customizer], [thisArg])

#

Assigns own enumerable properties of source object(s) to the destination object. Subsequent sources overwrite property assignments of previous sources. If customizer is provided it's invoked to produce the assigned values. The customizer is bound to thisArg and invoked with five arguments:
(objectValue, sourceValue, key, object, source).

Note: This method mutates object and is based on Object.assign.

别名(Aliases)

_.extend

参数

  1. object (Object): The destination object.
  2. [sources] (...Object): The source objects.
  3. [customizer] (Function): The function to customize assigned values.
  4. [thisArg] (*): The this binding of customizer.

返回值

(Object): Returns object.

例子

_.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
// => { 'user': 'fred', 'age': 40 }

// using a customizer callback
var defaults = _.partialRight(_.assign, function(value, other) {
  return _.isUndefined(value) ? other : value;
});

defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
// => { 'user': 'barney', 'age': 36 }

_.create(prototype, [properties])

#

Creates an object that inherits from the given prototype object. If a properties object is provided its own enumerable properties are assigned to the created object.

参数

  1. prototype (Object): The object to inherit from.
  2. [properties] (Object): The properties to assign to the object.

返回值

(Object): Returns the new 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])

#

Assigns own enumerable properties of source object(s) to the destination object for all destination properties that resolve to undefined. Once a property is set, additional values of the same property are ignored.

Note: This method mutates object.

参数

  1. object (Object): The destination object.
  2. [sources] (...Object): The source objects.

返回值

(Object): Returns object.

例子

_.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
// => { 'user': 'barney', 'age': 36 }

_.defaultsDeep(object, [sources])

#

This method is like _.defaults except that it recursively assigns default properties.

Note: This method mutates object.

参数

  1. object (Object): The destination object.
  2. [sources] (...Object): The source objects.

返回值

(Object): Returns object.

例子

_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
// => { 'user': { 'name': 'barney', 'age': 36 } }

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

#

This method is like _.find except that it returns the key of the first element predicate returns truthy for instead of the element itself.

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. object (Object): The object to search.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(string|undefined): Returns the key of the matched element, else undefined.

例子

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findKey(users, function(chr) {
  return chr.age < 40;
});
// => 'barney' (iteration order is not guaranteed)

// using the `_.matches` callback shorthand
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
_.findKey(users, 'active', false);
// => 'fred'

// using the `_.property` callback shorthand
_.findKey(users, 'active');
// => 'barney'

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

#

This method is like _.findKey except that it iterates over elements of a collection in the opposite order.

If a property name is provided for predicate the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. object (Object): The object to search.
  2. [predicate=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of predicate.

返回值

(string|undefined): Returns the key of the matched element, else undefined.

例子

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findLastKey(users, function(chr) {
  return chr.age < 40;
});
// => returns `pebbles` assuming `_.findKey` returns `barney`

// using the `_.matches` callback shorthand
_.findLastKey(users, { 'age': 36, 'active': true });
// => 'barney'

// using the `_.matchesProperty` callback shorthand
_.findLastKey(users, 'active', false);
// => 'fred'

// using the `_.property` callback shorthand
_.findLastKey(users, 'active');
// => 'pebbles'

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

#

Iterates over own and inherited enumerable properties of an object invoking iteratee for each property. The iteratee is bound to thisArg and invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

参数

  1. object (Object): The object to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns 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', and 'c' (iteration order is not guaranteed)

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

#

This method is like _.forIn except that it iterates over properties of object in the opposite order.

参数

  1. object (Object): The object to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns 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', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'

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

#

Iterates over own enumerable properties of an object invoking iteratee for each property. The iteratee is bound to thisArg and invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

参数

  1. object (Object): The object to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns object.

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

_.forOwn(new Foo, function(value, key) {
  console.log(key);
});
// => logs 'a' and 'b' (iteration order is not guaranteed)

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

#

This method is like _.forOwn except that it iterates over properties of object in the opposite order.

参数

  1. object (Object): The object to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns object.

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

_.forOwnRight(new Foo, function(value, key) {
  console.log(key);
});
// => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'

_.functions(object)

#

Creates an array of function property names from all enumerable properties, own and inherited, of object.

别名(Aliases)

_.methods

参数

  1. object (Object): The object to inspect.

返回值

(Array): Returns the new array of property names.

例子

_.functions(_);
// => ['after', 'ary', 'assign', ...]

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

#

Gets the property value at path of object. If the resolved value is undefined the defaultValue is used in its place.

参数

  1. object (Object): The object to query.
  2. path (Array|string): The path of the property to get.
  3. [defaultValue] (*): The value returned if the resolved value is undefined.

返回值

(*): Returns the resolved value.

例子

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)

#

Checks if path is a direct property.

参数

  1. object (Object): The object to query.
  2. path (Array|string): The path to check.

返回值

(boolean): Returns true if path is a direct property, else false.

例子

var object = { 'a': { 'b': { 'c': 3 } } };

_.has(object, 'a');
// => true

_.has(object, 'a.b.c');
// => true

_.has(object, ['a', 'b', 'c']);
// => true

_.invert(object, [multiValue])

#

Creates an object composed of the inverted keys and values of object. If object contains duplicate values, subsequent values overwrite property assignments of previous values unless multiValue is true.

参数

  1. object (Object): The object to invert.
  2. [multiValue] (boolean): Allow multiple values per key.

返回值

(Object): Returns the new inverted object.

例子

var object = { 'a': 1, 'b': 2, 'c': 1 };

_.invert(object);
// => { '1': 'c', '2': 'b' }

// with `multiValue`
_.invert(object, true);
// => { '1': ['a', 'c'], '2': ['b'] }

_.keys(object)

#

Creates an array of the own enumerable property names of object.

Note: Non-object values are coerced to objects. See the ES spec for more details.

参数

  1. object (Object): The object to query.

返回值

(Array): Returns the array of property names.

例子

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)

#

Creates an array of the own and inherited enumerable property names of object.

Note: Non-object values are coerced to objects.

参数

  1. object (Object): The object to query.

返回值

(Array): Returns the array of property names.

例子

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], [thisArg])

#

The opposite of _.mapValues; this method creates an object with the same values as object and keys generated by running each own enumerable property of object through iteratee.

参数

  1. object (Object): The object to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns the new mapped object.

例子

_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  return key + value;
});
// => { 'a1': 1, 'b2': 2 }

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

#

Creates an object with the same keys as object and values generated by running each own enumerable property of object through iteratee. The iteratee function is bound to thisArg and invoked with three arguments:
(value, key, object).

If a property name is provided for iteratee the created _.property style callback returns the property value of the given element.

If a value is also provided for thisArg the created _.matchesProperty style callback returns true for elements that have a matching property value, else false.

If an object is provided for iteratee the created _.matches style callback returns true for elements that have the properties of the given object, else false.

参数

  1. object (Object): The object to iterate over.
  2. [iteratee=_.identity] (Function|Object|string): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Object): Returns the new mapped object.

例子

_.mapValues({ 'a': 1, 'b': 2 }, function(n) {
  return n * 3;
});
// => { 'a': 3, 'b': 6 }

var users = {
  'fred':    { 'user': 'fred',    'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
};

// using the `_.property` callback shorthand
_.mapValues(users, 'age');
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)

_.merge(object, [sources], [customizer], [thisArg])

#

Recursively merges own enumerable properties of the source object(s), that don't resolve to undefined into the destination object. Subsequent sources overwrite property assignments of previous sources. If customizer is provided it's invoked to produce the merged values of the destination and source properties. If customizer returns undefined merging is handled by the method instead. The customizer is bound to thisArg and invoked with five arguments: (objectValue, sourceValue, key, object, source).

参数

  1. object (Object): The destination object.
  2. [sources] (...Object): The source objects.
  3. [customizer] (Function): The function to customize assigned values.
  4. [thisArg] (*): The this binding of customizer.

返回值

(Object): Returns object.

例子

var users = {
  'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
};

var ages = {
  'data': [{ 'age': 36 }, { 'age': 40 }]
};

_.merge(users, ages);
// => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }

// using a customizer callback
var object = {
  'fruits': ['apple'],
  'vegetables': ['beet']
};

var other = {
  'fruits': ['banana'],
  'vegetables': ['carrot']
};

_.merge(object, other, function(a, b) {
  if (_.isArray(a)) {
    return a.concat(b);
  }
});
// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }

_.omit(object, [predicate], [thisArg])

#

The opposite of _.pick; this method creates an object composed of the own and inherited enumerable properties of object that are not omitted.

参数

  1. object (Object): The source object.
  2. [predicate] (Function|...(string|string[]): The function invoked per iteration or property names to omit, specified as individual property names or arrays of property names.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Object): Returns the new object.

例子

var object = { 'user': 'fred', 'age': 40 };

_.omit(object, 'age');
// => { 'user': 'fred' }

_.omit(object, _.isNumber);
// => { 'user': 'fred' }

_.pairs(object)

#

Creates a two dimensional array of the key-value pairs for object, e.g. [[key1, value1], [key2, value2]].

参数

  1. object (Object): The object to query.

返回值

(Array): Returns the new array of key-value pairs.

例子

_.pairs({ 'barney': 36, 'fred': 40 });
// => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)

_.pick(object, [predicate], [thisArg])

#

Creates an object composed of the picked object properties. Property names may be specified as individual arguments or as arrays of property names. If predicate is provided it's invoked for each property of object picking the properties predicate returns truthy for. The predicate is bound to thisArg and invoked with three arguments: (value, key, object).

参数

  1. object (Object): The source object.
  2. [predicate] (Function|...(string|string[]): The function invoked per iteration or property names to pick, specified as individual property names or arrays of property names.
  3. [thisArg] (*): The this binding of predicate.

返回值

(Object): Returns the new object.

例子

var object = { 'user': 'fred', 'age': 40 };

_.pick(object, 'user');
// => { 'user': 'fred' }

_.pick(object, _.isString);
// => { 'user': 'fred' }

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

#

This method is like _.get except that if the resolved value is a function it's invoked with the this binding of its parent object and its result is returned.

参数

  1. object (Object): The object to query.
  2. path (Array|string): The path of the property to resolve.
  3. [defaultValue] (*): The value returned if the resolved value is undefined.

返回值

(*): Returns the resolved value.

例子

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.b.c', 'default');
// => 'default'

_.result(object, 'a.b.c', _.constant('default'));
// => 'default'

_.set(object, path, value)

#

Sets the property value of path on object. If a portion of path does not exist it's created.

参数

  1. object (Object): The object to augment.
  2. path (Array|string): The path of the property to set.
  3. value (*): The value to set.

返回值

(Object): Returns 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

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

#

An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of running each of its own enumerable properties through iteratee, with each invocation potentially mutating the accumulator object. The iteratee is bound to thisArg and invoked with four arguments: (accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

参数

  1. object (Array|Object): The object to iterate over.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [accumulator] (*): The custom accumulator value.
  4. [thisArg] (*): The this binding of iteratee.

返回值

(*): Returns the accumulated value.

例子

_.transform([2, 3, 4], function(result, n) {
  result.push(n *= n);
  return n % 2 == 0;
});
// => [4, 9]

_.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
  result[key] = n * 3;
});
// => { 'a': 3, 'b': 6 }

_.values(object)

#

Creates an array of the own enumerable property values of object.

Note: Non-object values are coerced to objects.

参数

  1. object (Object): The object to query.

返回值

(Array): Returns the array of property values.

例子

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)

#

Creates an array of the own and inherited enumerable property values of object.

Note: Non-object values are coerced to objects.

参数

  1. object (Object): The object to query.

返回值

(Array): Returns the array of property values.

例子

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

_.valuesIn(new Foo);
// => [1, 2, 3] (iteration order is not guaranteed)

“String” Methods

_.camelCase([string=''])

#

Converts string to camel case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the camel cased string.

例子

_.camelCase('Foo Bar');
// => 'fooBar'

_.camelCase('--foo-bar');
// => 'fooBar'

_.camelCase('__foo_bar__');
// => 'fooBar'

_.capitalize([string=''])

#

Capitalizes the first character of string.

参数

  1. [string=''] (string): The string to capitalize.

返回值

(string): Returns the capitalized string.

例子

_.capitalize('fred');
// => 'Fred'

_.deburr([string=''])

#

Deburrs string by converting latin-1 supplementary letters#Character_table) to basic latin letters and removing combining diacritical marks.

参数

  1. [string=''] (string): The string to deburr.

返回值

(string): Returns the deburred string.

例子

_.deburr('déjà vu');
// => 'deja vu'

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

#

Checks if string ends with the given target string.

参数

  1. [string=''] (string): The string to search.
  2. [target] (string): The string to search for.
  3. [position=string.length] (number): The position to search from.

返回值

(boolean): Returns true if string ends with target, else false.

例子

_.endsWith('abc', 'c');
// => true

_.endsWith('abc', 'b');
// => false

_.endsWith('abc', 'b', 2);
// => true

_.escape([string=''])

#

Converts the characters "&", "<", ">", '"', "'", and "`", in string to their corresponding HTML entities.

Note: No other characters are escaped. To escape additional characters use a third-party library like he.

Though the ">" character is escaped for symmetry, characters like ">" and "/" don't need escaping in HTML and have no special meaning unless they're part of a tag or unquoted attribute value. See Mathias Bynens's article (under "semi-related fun fact") for more details.

Backticks are escaped because in Internet Explorer < 9, they can break out of attribute values or HTML comments. See #59, #102, #108, and #133 of the HTML5 Security Cheatsheet for more details.

When working with HTML you should always quote attribute values to reduce XSS vectors.

参数

  1. [string=''] (string): The string to escape.

返回值

(string): Returns the escaped string.

例子

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

_.escapeRegExp([string=''])

#

Escapes the RegExp special characters "\", "/", "^", "$", ".", "|", "?", "*", "+", "(", ")", "[", "]", "{" and "}" in string.

参数

  1. [string=''] (string): The string to escape.

返回值

(string): Returns the escaped string.

例子

_.escapeRegExp('[lodash](https://lodash.com/)');
// => '\[lodash\]\(https:\/\/lodash\.com\/\)'

_.kebabCase([string=''])

#

Converts string to kebab case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the kebab cased string.

例子

_.kebabCase('Foo Bar');
// => 'foo-bar'

_.kebabCase('fooBar');
// => 'foo-bar'

_.kebabCase('__foo_bar__');
// => 'foo-bar'

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

#

Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length.

参数

  1. [string=''] (string): The string to pad.
  2. [length=0] (number): The padding length.
  3. [chars=' '] (string): The string used as padding.

返回值

(string): Returns the padded string.

例子

_.pad('abc', 8);
// => '  abc   '

_.pad('abc', 8, '_-');
// => '_-abc_-_'

_.pad('abc', 3);
// => 'abc'

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

#

Pads string on the left side if it's shorter than length. Padding characters are truncated if they exceed length.

参数

  1. [string=''] (string): The string to pad.
  2. [length=0] (number): The padding length.
  3. [chars=' '] (string): The string used as padding.

返回值

(string): Returns the padded string.

例子

_.padLeft('abc', 6);
// => '   abc'

_.padLeft('abc', 6, '_-');
// => '_-_abc'

_.padLeft('abc', 3);
// => 'abc'

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

#

Pads string on the right side if it's shorter than length. Padding characters are truncated if they exceed length.

参数

  1. [string=''] (string): The string to pad.
  2. [length=0] (number): The padding length.
  3. [chars=' '] (string): The string used as padding.

返回值

(string): Returns the padded string.

例子

_.padRight('abc', 6);
// => 'abc   '

_.padRight('abc', 6, '_-');
// => 'abc_-_'

_.padRight('abc', 3);
// => 'abc'

_.parseInt(string, [radix])

#

Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used unless value is a hexadecimal, in which case a radix of 16 is used.

Note: This method aligns with the ES5 implementation of parseInt.

参数

  1. string (string): The string to convert.
  2. [radix] (number): The radix to interpret value by.

返回值

(number): Returns the converted integer.

例子

_.parseInt('08');
// => 8

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

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

#

Repeats the given string n times.

参数

  1. [string=''] (string): The string to repeat.
  2. [n=0] (number): The number of times to repeat the string.

返回值

(string): Returns the repeated string.

例子

_.repeat('*', 3);
// => '***'

_.repeat('abc', 2);
// => 'abcabc'

_.repeat('abc', 0);
// => ''

_.snakeCase([string=''])

#

Converts string to snake case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the snake cased string.

例子

_.snakeCase('Foo Bar');
// => 'foo_bar'

_.snakeCase('fooBar');
// => 'foo_bar'

_.snakeCase('--foo-bar');
// => 'foo_bar'

_.startCase([string=''])

#

Converts string to start case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the start cased string.

例子

_.startCase('--foo-bar');
// => 'Foo Bar'

_.startCase('fooBar');
// => 'Foo Bar'

_.startCase('__foo_bar__');
// => 'Foo Bar'

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

#

Checks if string starts with the given target string.

参数

  1. [string=''] (string): The string to search.
  2. [target] (string): The string to search for.
  3. [position=0] (number): The position to search from.

返回值

(boolean): Returns true if string starts with target, else false.

例子

_.startsWith('abc', 'a');
// => true

_.startsWith('abc', 'b');
// => false

_.startsWith('abc', 'b', 1);
// => true

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

#

Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data properties may be accessed as free variables in the template. If a setting object is provided it takes precedence over _.templateSettings values.

Note: In the development build _.template utilizes sourceURLs for easier debugging.

For more information on precompiling templates see lodash's custom builds documentation.

For more information on Chrome extension sandboxes see Chrome's extensions documentation.

参数

  1. [string=''] (string): The template string.
  2. [options] (Object): The options object.
  3. [options.escape] (RegExp): The HTML "escape" delimiter.
  4. [options.evaluate] (RegExp): The "evaluate" delimiter.
  5. [options.imports] (Object): An object to import into the template as free variables.
  6. [options.interpolate] (RegExp): The "interpolate" delimiter.
  7. [options.sourceURL] (string): The sourceURL of the template's compiled source.
  8. [options.variable] (string): The data object variable name.

返回值

(Function): Returns the compiled template function.

例子

// using the "interpolate" delimiter to create a compiled template
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'

// using the HTML "escape" delimiter to escape data property values
var compiled = _.template('<b><%- value %></b>');
compiled({ 'value': '<script>' });
// => '<b>&lt;script&gt;</b>'

// using 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>'

// using the internal `print` function in "evaluate" delimiters
var compiled = _.template('<% print("hello " + user); %>!');
compiled({ 'user': 'barney' });
// => 'hello barney!'

// using the ES delimiter as an alternative to the default "interpolate" delimiter
var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!'

// using custom template delimiters
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'

// using backslashes to treat delimiters as plain text
var compiled = _.template('<%= "\\<%- value %\\>" %>');
compiled({ 'value': 'ignored' });
// => '<%- value %>'

// using 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>'

// using 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

// using 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;
// }

// using the `source` property to inline compiled templates for meaningful
// line numbers in error messages and a stack trace
fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  var JST = {\
    "main": ' + _.template(mainText).source + '\
  };\
');

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

#

Removes leading and trailing whitespace or specified characters from string.

参数

  1. [string=''] (string): The string to trim.
  2. [chars=whitespace] (string): The characters to trim.

返回值

(string): Returns the trimmed string.

例子

_.trim('  abc  ');
// => 'abc'

_.trim('-_-abc-_-', '_-');
// => 'abc'

_.map(['  foo  ', '  bar  '], _.trim);
// => ['foo', 'bar']

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

#

Removes leading whitespace or specified characters from string.

参数

  1. [string=''] (string): The string to trim.
  2. [chars=whitespace] (string): The characters to trim.

返回值

(string): Returns the trimmed string.

例子

_.trimLeft('  abc  ');
// => 'abc  '

_.trimLeft('-_-abc-_-', '_-');
// => 'abc-_-'

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

#

Removes trailing whitespace or specified characters from string.

参数

  1. [string=''] (string): The string to trim.
  2. [chars=whitespace] (string): The characters to trim.

返回值

(string): Returns the trimmed string.

例子

_.trimRight('  abc  ');
// => '  abc'

_.trimRight('-_-abc-_-', '_-');
// => '-_-abc'

_.trunc([string=''], [options], [options.length=30], [options.omission='...'], [options.separator])

#

Truncates string if it's longer than the given maximum string length. The last characters of the truncated string are replaced with the omission string which defaults to "...".

参数

  1. [string=''] (string): The string to truncate.
  2. [options] (Object|number): The options object or maximum string length.
  3. [options.length=30] (number): The maximum string length.
  4. [options.omission='...'] (string): The string to indicate text is omitted.
  5. [options.separator] (RegExp|string): The separator pattern to truncate to.

返回值

(string): Returns the truncated string.

例子

_.trunc('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'

_.trunc('hi-diddly-ho there, neighborino', 24);
// => 'hi-diddly-ho there, n...'

_.trunc('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
});
// => 'hi-diddly-ho there,...'

_.trunc('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': /,? +/
});
// => 'hi-diddly-ho there...'

_.trunc('hi-diddly-ho there, neighborino', {
  'omission': ' [...]'
});
// => 'hi-diddly-ho there, neig [...]'

_.unescape([string=''])

#

The inverse of _.escape; this method converts the HTML entities &amp;, &lt;, &gt;, &quot;, &#39;, and &#96; in string to their corresponding characters.

Note: No other HTML entities are unescaped. To unescape additional HTML entities use a third-party library like he.

参数

  1. [string=''] (string): The string to unescape.

返回值

(string): Returns the unescaped string.

例子

_.unescape('fred, barney, &amp; pebbles');
// => 'fred, barney, & pebbles'

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

#

Splits string into an array of its words.

参数

  1. [string=''] (string): The string to inspect.
  2. [pattern] (RegExp|string): The pattern to match words.

返回值

(Array): Returns the words of string.

例子

_.words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']

_.words('fred, barney, & pebbles', /[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']

“Utility” Methods

_.attempt(func)

#

Attempts to invoke func, returning either the result or the caught error object. Any additional arguments are provided to func when it's invoked.

参数

  1. func (Function): The function to attempt.

返回值

(*): Returns the func result or error object.

例子

// avoid throwing errors for invalid selectors
var elements = _.attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');

if (_.isError(elements)) {
  elements = [];
}

_.callback([func=_.identity], [thisArg])

#

Creates a function that invokes func with the this binding of thisArg and arguments of the created function. If func is a property name the created callback returns the property value for a given element. If func is an object the created callback returns true for elements that contain the equivalent object properties, otherwise it returns false.

别名(Aliases)

_.iteratee

参数

  1. [func=_.identity] (*): The value to convert to a callback.
  2. [thisArg] (*): The this binding of func.

返回值

(Function): Returns the callback.

例子

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

// wrap to create custom callback shorthands
_.callback = _.wrap(_.callback, function(callback, func, thisArg) {
  var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
  if (!match) {
    return callback(func, thisArg);
  }
  return function(object) {
    return match[2] == 'gt'
      ? object[match[1]] > match[3]
      : object[match[1]] < match[3];
  };
});

_.filter(users, 'age__gt36');
// => [{ 'user': 'fred', 'age': 40 }]

_.constant(value)

#

Creates a function that returns value.

参数

  1. value (*): The value to return from the new function.

返回值

(Function): Returns the new function.

例子

var object = { 'user': 'fred' };
var getter = _.constant(object);

getter() === object;
// => true

_.identity(value)

#

This method returns the first argument provided to it.

参数

  1. value (*): Any value.

返回值

(*): Returns value.

例子

var object = { 'user': 'fred' };

_.identity(object) === object;
// => true

_.matches(source)

#

Creates a function that performs a deep comparison between a given object and source, returning true if the given object has equivalent property values, else false.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties. For comparing a single own or inherited property value see _.matchesProperty.

参数

  1. source (Object): The object of property values to match.

返回值

(Function): Returns the new function.

例子

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, _.matches({ 'age': 40, 'active': false }));
// => [{ 'user': 'fred', 'age': 40, 'active': false }]

_.matchesProperty(path, srcValue)

#

Creates a function that compares the property value of path on a given object to value.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties.

参数

  1. path (Array|string): The path of the property to get.
  2. srcValue (*): The value to match.

返回值

(Function): Returns the new function.

例子

var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];

_.find(users, _.matchesProperty('user', 'fred'));
// => { 'user': 'fred' }

_.method(path, [args])

#

Creates a function that invokes the method at path on a given object. Any additional arguments are provided to the invoked method.

参数

  1. path (Array|string): The path of the method to invoke.
  2. [args] (...*): The arguments to invoke the method with.

返回值

(Function): Returns the new function.

例子

var objects = [
  { 'a': { 'b': { 'c': _.constant(2) } } },
  { 'a': { 'b': { 'c': _.constant(1) } } }
];

_.map(objects, _.method('a.b.c'));
// => [2, 1]

_.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
// => [1, 2]

_.methodOf(object, [args])

#

The opposite of _.method; this method creates a function that invokes the method at a given path on object. Any additional arguments are provided to the invoked method.

参数

  1. object (Object): The object to query.
  2. [args] (...*): The arguments to invoke the method with.

返回值

(Function): Returns the new function.

例子

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])

#

Adds all own enumerable function properties of a source object to the destination object. If object is a function then methods are added to its prototype as well.

Note: Use _.runInContext to create a pristine lodash function to avoid conflicts caused by modifying the original.

参数

  1. [object=lodash] (Function|Object): The destination object.
  2. source (Object): The object of functions to add.
  3. [options] (Object): The options object.
  4. [options.chain=true] (boolean): Specify whether the functions added are chainable.

返回值

(Function|Object): Returns 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()

#

Reverts the _ variable to its previous value and returns a reference to the lodash function.

返回值

(Function): Returns the lodash function.

例子

var lodash = _.noConflict();

_.noop()

#

A no-operation function that returns undefined regardless of the arguments it receives.

例子

var object = { 'user': 'fred' };

_.noop(object) === undefined;
// => true

_.property(path)

#

Creates a function that returns the property value at path on a given object.

参数

  1. path (Array|string): The path of the property to get.

返回值

(Function): Returns the new function.

例子

var objects = [
  { 'a': { 'b': { 'c': 2 } } },
  { 'a': { 'b': { 'c': 1 } } }
];

_.map(objects, _.property('a.b.c'));
// => [2, 1]

_.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
// => [1, 2]

_.propertyOf(object)

#

The opposite of _.property; this method creates a function that returns the property value at a given path on object.

参数

  1. object (Object): The object to query.

返回值

(Function): Returns the new function.

例子

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])

#

Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. If end is not specified it's set to start with start then set to 0. If end is less than start a zero-length range is created unless a negative step is specified.

参数

  1. [start=0] (number): The start of the range.
  2. end (number): The end of the range.
  3. [step=1] (number): The value to increment or decrement by.

返回值

(Array): Returns the new array of numbers.

例子

_.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);
// => []

_.runInContext([context=root])

#

Create a new pristine lodash function using the given context object.

参数

  1. [context=root] (Object): The context object.

返回值

(Function): Returns a new lodash function.

例子

_.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

// using `context` to mock `Date#getTime` use in `_.now`
var mock = _.runInContext({
  'Date': function() {
    return { 'getTime': getTimeMock };
  }
});

// or creating a suped-up `defer` in Node.js
var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;

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

#

Invokes the iteratee function n times, returning an array of the results of each invocation. The iteratee is bound to thisArg and invoked with one argument; (index).

参数

  1. n (number): The number of times to invoke iteratee.
  2. [iteratee=_.identity] (Function): The function invoked per iteration.
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array): Returns the array of results.

例子

var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
// => [3, 6, 4]

_.times(3, function(n) {
  mage.castSpell(n);
});
// => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`

_.times(3, function(n) {
  this.cast(n);
}, mage);
// => also invokes `mage.castSpell(n)` three times

_.uniqueId([prefix])

#

Generates a unique ID. If prefix is provided the ID is appended to it.

参数

  1. [prefix] (string): The value to prefix the ID with.

返回值

(string): Returns the unique ID.

例子

_.uniqueId('contact_');
// => 'contact_104'

_.uniqueId();
// => '105'

Methods

_.templateSettings.imports._

#

A reference to the lodash function.


Properties

_.VERSION

#

(string): The semantic version number.


_.support

#

(Object): An object environment feature flags.


_.support.enumErrorProps

#

(boolean): Detect if name or message properties of Error.prototype are enumerable by default (IE < 9, Safari < 5.1).


_.support.enumPrototypes

#

(boolean): Detect if prototype properties are enumerable by default.

Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 (if the prototype or a property on the prototype has been set) incorrectly set the [[Enumerable]] value of a function's prototype property to true.


_.support.nonEnumShadows

#

(boolean): Detect if properties shadowing those on Object.prototype are non-enumerable.

In IE < 9 an object's own properties, shadowing non-enumerable ones, are made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).


_.support.ownLast

#

(boolean): Detect if own properties are iterated after inherited properties (IE < 9).


_.support.spliceObjects

#

(boolean): Detect if Array#shift and Array#splice augment array-like objects correctly.

Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array shift() and splice() functions that fail to remove the last element, value[0], of array-like objects even though the "length" property is set to 0. The shift() method is buggy in compatibility modes of IE 8, while splice() is buggy regardless of mode in IE < 9.


_.support.unindexedChars

#

(boolean): Detect lack of support for accessing string characters by index.

IE < 8 can't access characters by index. IE 8 can only access characters by index on string literals, not string objects.


_.templateSettings

#

(Object): By default, the template delimiters used by lodash are like those in embedded Ruby (ERB). Change the following template settings to use alternative delimiters.


_.templateSettings.escape

#

(RegExp): Used to detect data property values to be HTML-escaped.


_.templateSettings.evaluate

#

(RegExp): Used to detect code to be evaluated.


_.templateSettings.imports

#

(Object): Used to import variables into the compiled template.


_.templateSettings.interpolate

#

(RegExp): Used to detect data property values to inject.


_.templateSettings.variable

#

(string): Used to reference the data object in the template text.