lodash v3.10.1 API中文版

翻译作者: giscafer

博客:http://giscafer.com

翻译说明:根据本人个人的理解而译,英文水平有限,可能存在有专业术语描述不是很正确的地方

Array

Chain

Collection

Date

Function

Lang

Math

Number

Object

String

Utility

Methods

Properties

“Array” Methods

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

#

根据size指定的长度将数组array拆分成块数组,如果数组array无法拆分,则保留原样

参数

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

返回值

(Array): 返回一个包含拆分块数组的新数组(将块数组组成的二维数组).

例子

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

_.compact(array)

#

移除数组中所有的假值. 例如 false, null, 0, "", undefined, 和 NaN 都是“假值”.

参数

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

返回值

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

例子

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

_.difference(array, [values])

#

过滤掉array里边和values一样的元素,使用全等方式判断===

参数

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

返回值

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

例子

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

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

#

从数组的第n个元素开始分割数组array(从左数)

参数

  1. array (Array): 查询分割数组
  2. [n=1] (number): 分割的起始值,默认是从1

返回值

(Array): 返回分割后的数组array.

例子

  1. _.drop([1, 2, 3]);
  2. // => [2, 3] 默认是1开始的
  3. _.drop([1, 2, 3], 2);
  4. // => [3]
  5. _.drop([1, 2, 3], 5);
  6. // => []
  7. _.drop([1, 2, 3], 0);
  8. // => [1, 2, 3]

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

#

Creates a slice of array with n elements dropped from the end. 倒数起算,从数组的倒数n位开始分割数组(从右数)

参数

  1. array (Array): 需要查询的数组
  2. [n=1] (number): 分割的起始值,(默认是1)

返回值

(Array): 返回分割后的数组 array.

例子

  1. _.dropRight([1, 2, 3]);
  2. // => [1, 2]
  3. _.dropRight([1, 2, 3], 2);
  4. // => [1]
  5. _.dropRight([1, 2, 3], 5);
  6. // => []
  7. _.dropRight([1, 2, 3], 0);
  8. // => [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): 返回截取元素后的数组

例子

  1. _.dropRightWhile([1, 2, 3], function(n) {
  2. return n > 1;
  3. });
  4. // => [1]
  5. _.dropRightWhile([5,,1, 2, 3], function(n) {
  6. return n > 1;
  7. });
  8. // => [5,1]
  9. var users = [
  10. { 'user': 'barney', 'active': true },
  11. { 'user': 'fred', 'active': false },
  12. { 'user': 'pebbles', 'active': false }
  13. ];
  14. // _.dropRightWhile(users, { 'user': 'pebbles', 'active': false })将返回
  15. //[{ 'user': 'barney', 'active': true },{ 'user': 'fred', 'active': false }]
  16. //使用了`_.matches` (元素是否匹配)
  17. _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
  18. // => ['barney', 'fred']
  19. // 使用`_.matchesProperty` (属性是否匹配,比如下边意思就是active=false的users元素有哪些)
  20. //_.dropRightWhile(users, 'active', false)将返回[{ 'user': 'barney', 'active': true }]
  21. _.pluck(_.dropRightWhile(users, 'active', false), 'user');
  22. // => ['barney']
  23. // 使用 `_.property` (是否含有active属性)
  24. //_.dropRightWhile(users, 'active')返回
  25. //[{ 'user': 'barney', 'active': true },
  26. //{ 'user': 'fred', 'active': false },
  27. //{ 'user': 'pebbles', 'active': false }];
  28. _.pluck(_.dropRightWhile(users, 'active'), 'user');
  29. // => ['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): 返回截取元素后的数组

例子

  1. _.dropWhile([1, 2, 3], function(n) {
  2. return n < 3;
  3. });
  4. // => [3]
  5. var users = [
  6. { 'user': 'barney', 'active': false },
  7. { 'user': 'fred', 'active': false },
  8. { 'user': 'pebbles', 'active': true }
  9. ];
  10. // using the `_.matches` callback shorthand
  11. _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
  12. // => ['fred', 'pebbles']
  13. // using the `_.matchesProperty` callback shorthand
  14. _.pluck(_.dropWhile(users, 'active', false), 'user');
  15. // => ['pebbles']
  16. // using the `_.property` callback shorthand
  17. _.pluck(_.dropWhile(users, 'active'), 'user');
  18. // => ['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): 结束位置(不含)
  5. 如果startend省略,则value填充array全部元素

    返回值

    (Array): 返回 array .

例子

  1. var array = [1, 2, 3];
  2. _.fill(array, 'a');
  3. console.log(array);
  4. // => ['a', 'a', 'a']
  5. _.fill(Array(3), 2);
  6. // => [2, 2, 2]
  7. _.fill([4, 6, 8], '*', 1, 2);
  8. // => [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.

例子

  1. var users = [
  2. { 'user': 'barney', 'active': false },
  3. { 'user': 'fred', 'active': false },
  4. { 'user': 'pebbles', 'active': true }
  5. ];
  6. _.findIndex(users, function(chr) {
  7. return chr.user == 'barney';
  8. });
  9. // => 0
  10. // using the `_.matches` callback shorthand
  11. _.findIndex(users, { 'user': 'fred', 'active': false });
  12. // => 1
  13. // using the `_.matchesProperty` callback shorthand
  14. _.findIndex(users, 'active', false);
  15. // => 0
  16. // using the `_.property` callback shorthand
  17. _.findIndex(users, 'active');
  18. // => 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.

例子

  1. var users = [
  2. { 'user': 'barney', 'active': true },
  3. { 'user': 'fred', 'active': false },
  4. { 'user': 'pebbles', 'active': false }
  5. ];
  6. _.findLastIndex(users, function(chr) {
  7. return chr.user == 'pebbles';
  8. });
  9. // => 2
  10. // using the `_.matches` callback shorthand
  11. _.findLastIndex(users, { 'user': 'barney', 'active': true });
  12. // => 0
  13. // using the `_.matchesProperty` callback shorthand
  14. _.findLastIndex(users, 'active', false);
  15. // => 2
  16. // using the `_.property` callback shorthand
  17. _.findLastIndex(users, 'active');
  18. // => 0

_.first(array)

#

获取数组 array的第一个元素

别名(Aliases)

_.head

参数

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

返回值

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

例子

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

_.flatten(array, [isDeep])

#

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

参数

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

返回值

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

例子

  1. _.flatten([1, [2, 3, [4]]]);
  2. // => [1, 2, 3, [4]] //默认只减少一维
  3. // using `isDeep`
  4. _.flatten([1, [2, 3, [4]]], true);
  5. // => [1, 2, 3, 4] //深递归最终数组只有一维

_.flattenDeep(array)

#

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

参数

  1. array (Array): 需要

返回值

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

例子

  1. _.flattenDeep([1, [2, 3, [4]]]);
  2. // => [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.

例子

  1. _.indexOf([1, 2, 1, 2], 2);
  2. // => 1
  3. // using `fromIndex`
  4. _.indexOf([1, 2, 1, 2], 2, 2);
  5. // => 3
  6. // performing a binary search
  7. _.indexOf([1, 1, 2, 2], 2, true);
  8. // => 2

_.initial(array)

#

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

参数

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

返回值

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

例子

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

_.intersection([arrays])

#

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

参数

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

返回值

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

例子

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

_.last(array)

#

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

参数

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

返回值

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

例子

  1. _.last([1, 2, 3]);
  2. // => 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.

例子

  1. _.lastIndexOf([1, 2, 1, 2], 2);
  2. // => 3
  3. // using `fromIndex`
  4. _.lastIndexOf([1, 2, 1, 2], 2, 2);
  5. // => 1
  6. // performing a binary search
  7. _.lastIndexOf([1, 1, 2, 2], 2, true);
  8. // => 3

_.pull(array, [values])

#

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

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

参数

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

返回值

(Array): 返回数组 array.

例子

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

_.pullAt(array, [indexes])

#

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

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

参数

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

返回值

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

例子

  1. var array = [5, 10, 15, 20];
  2. var evens = _.pullAt(array, 1, 3);
  3. console.log(array);
  4. // => [5, 15]
  5. console.log(evens);
  6. // => [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): 返回被移除元素组成的数组

例子

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

_.rest(array)

#

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

别名(Aliases)

_.tail

参数

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

返回值

(Array): 返回截取的 array.

例子

  1. _.rest([1, 2, 3]);
  2. // => [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])

#

在对一个有序数组array进行插入的时候,返回value应该插入的位置。从左向右计算。

参数

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

返回值

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

例子

  1. _.sortedIndex([30, 50], 40);
  2. // => 1
  3. _.sortedIndex([4, 4, 5, 5], 5);
  4. // => 2
  5. var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
  6. // using an iteratee function
  7. _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
  8. return this.data[word];
  9. }, dict);
  10. // => 1
  11. // using the `_.property` callback shorthand
  12. _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
  13. // => 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位置的索引值

例子

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

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

#

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

参数

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

返回值

(Array): 返回取得的数组

例子

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

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

#

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

参数

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

返回值

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

例子

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

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

#

从数组右侧开发,取出满足条件的数据元素.

参数

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

返回值

(Array): 返回取出的元素组成的数组 array.

例子

  1. _.takeRightWhile([1, 2, 3], function(n) {
  2. return n > 1;
  3. });
  4. // => [2, 3]
  5. var users = [
  6. { 'user': 'barney', 'active': true },
  7. { 'user': 'fred', 'active': false },
  8. { 'user': 'pebbles', 'active': false }
  9. ];
  10. // using the `_.matches` callback shorthand
  11. _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
  12. // => ['pebbles']
  13. // using the `_.matchesProperty` callback shorthand
  14. _.pluck(_.takeRightWhile(users, 'active', false), 'user');
  15. // => ['fred', 'pebbles']
  16. // using the `_.property` callback shorthand
  17. _.pluck(_.takeRightWhile(users, 'active'), 'user');
  18. // => []

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

#

原理同takeRightWhile,不过takeWhile方法是从左到右查询。

参数

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

返回值

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

例子

  1. _.takeWhile([1, 2, 3], function(n) {
  2. return n < 3;
  3. });
  4. // => [1, 2]
  5. var users = [
  6. { 'user': 'barney', 'active': false },
  7. { 'user': 'fred', 'active': false},
  8. { 'user': 'pebbles', 'active': true }
  9. ];
  10. // using the `_.matches` callback shorthand
  11. _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
  12. // => ['barney']
  13. // using the `_.matchesProperty` callback shorthand
  14. _.pluck(_.takeWhile(users, 'active', false), 'user');
  15. // => ['barney', 'fred']
  16. // using the `_.property` callback shorthand
  17. _.pluck(_.takeWhile(users, 'active'), 'user');
  18. // => []

_.union([arrays])

#

对提供的数组元素使用SameValueZero方式做比较(全等),去除相等的元素(相当于数学中的集合)。

参数

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

返回值

(Array): 返回一个新的组合数组

例子

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

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

#

保留满足条件第一次出现的元素,对已经排序的数组可以使用true参数来执行更快的搜索算法,如果提供一个iteratee函数遍历数组中每个元素来生成标准的唯一性 计算,iteratee is bound to thisArg and invoked with three arguments: (value, index, array).

简单理解就是取出满足条件的元素,并且取出的元素是第一次出现的那一个

别名(Aliases)

_.unique

参数

  1. array (Array): 需要检查的数组.
  2. [isSorted] (boolean): 声明数组是否排序过.
  3. [iteratee] (Function|Object|string): 遍历元素的条件,可以是方法,对象或者字符串.
  4. [thisArg] (*): The this binding of iteratee.

返回值

(Array): 返回新的duplicate-value-free数组.

例子

  1. _.uniq([2, 1, 2]);
  2. // => [2, 1]
  3. // using `isSorted`
  4. _.uniq([1, 1, 2], true);
  5. // => [1, 2]
  6. // using an iteratee function
  7. _.uniq([1, 2.5, 1.5, 2], function(n) {
  8. return this.floor(n);
  9. }, Math);
  10. // => [1, 2.5]
  11. // using the `_.property` callback shorthand
  12. _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
  13. // => [{ 'x': 1 }, { 'x': 2 }]

_.unzip(array)

#

和方法 _.zip 类似,除了它接受一个分组的数组并创建一个数组元素重组pre-zip元素配置. 也就是_.zip的相反操作

参数

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

返回值

(Array): 返回新的重组数组.

例子

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

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

#

和方法 _.unzip类似,除了它接受一个iteratee方法指定应该如何重新集结值的总和。方法iteratee绑定thisArg四个参数: (accumulator, value, index, group).

参数

  1. array (Array): 需要重组的数组
  2. [iteratee] (Function): 将重新集结值的函数。
  3. [thisArg] (*): The this binding of iteratee.

返回值

(Array): 返回重新重组的数组

例子

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

_.without(array, [values])

#

使用SameValueZero平等的比较(全等===),创建一个数组不包括所有提供的值

参数

  1. array (Array): 过滤的数组.
  2. [values] (…*): 排除的值.

返回值

(Array): 返回过滤排除值后的新数组

例子

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

_.xor([arrays])

#

根据symmetric difference所提供的数组,创建一个惟一值元素的数组

参数

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

返回值

(Array): 返回新数组.

例子

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

_.zip([arrays])

#

创建一个分组元素的数组,第一个包含第一给定数组的元素,第二个包含第二个元素给定的数组,等等。

参数

  1. [arrays] (…Array): 参数数组

返回值

(Array): 返回重新分组的数组.

例子

  1. _.zip(['fred', 'barney'], [30, 40], [true, false]);
  2. // => [['fred', 30, true], ['barney', 40, false]]
  3. _.zip(['fred', 'barney','a']);
  4. //=> [['fred'], ['barney'], ['a']]

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

#

和方法_.pairs相反; 这个方法返回一个对象由数组的属性的名称和值. 提供一个二维数组, e.g. [[key1, value1], [key2, value2]] 或者是两个数组, 一个是属性名数组,一个是对应属性名值的数组.

别名(Aliases)

_.object

参数

  1. props (Array): 属性名
  2. [values=[]] (Array): 属性值

返回值

(Object): 返回一个新对象.

例子

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

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

#

该方法类似 _.zip 除了接受一个iteratee方法指定应该如何结合组合值.

参数

  1. [arrays] (…Array): 执行的数组.
  2. [iteratee] (Function): 结合分组值的函数.
  3. [thisArg] (*): The this binding of iteratee.

返回值

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

例子

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

“Chain” Methods

_(value)

#

_(value)建立了一个隐式链对象,可以把那些能操作并返回arrays(数组)、collections(集合)、functions(函数)的.Methods(lodash的函数)串起来。 那些能返回“唯一值(single value)”或者可能返回原生数据类型(primitive value)会自动结束链式反应。 而显式链则用_.chain的方式实现延迟计算,即:求值操作等到 _value()被调用时再执行。

延迟计算允许一些方法支持shortcut fusion 。由于执行被延后了,因此lodash可以进行shortcut fusion这样的优化,通过合并链式iteratee大大降低迭代的次数。

链式支持自定义构建只要_#value的方法直接或间接地包含在构建

另外,lodash wrappers 还支持ArrayString的一些方法

支持wrapper的Array方法有:
concat, join, pop, push, reverse, shift, slice, sort, splice, and unshift

支持wrapperString方法有:
replace and split

支持shortcut fusion的方法有:
compact, drop, dropRight, dropRightWhile, dropWhile, filter, first, initial, last, map, pluck, reject, rest, reverse, slice, take, takeRight, takeRightWhile, takeWhile, toArray, and where

可以链式反应的wrapper方法有:
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

缺省情况下不能加在链条中间的wrapper方法有:
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

翻译作者: giscafer


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): 返回一个新的 lodash wrapper 实例.

例子

  1. var wrapped = _([1, 2, 3]);
  2. // 隐式链中,reduce是属于不能直接加在"链条中间"(not chainable)的,所以能立即执行计算
  3. wrapped.reduce(function(total, n) {
  4. return total + n;
  5. });
  6. // => 6
  7. // 而map是chainable的
  8. var squares = wrapped.map(function(n) {
  9. return n * n;
  10. });
  11. //所以不调用value()时返回的并不是一个Array而是一个wrapper
  12. _.isArray(squares);
  13. // => false
  14. //调用了value后返回的就是一个Array了
  15. _.isArray(squares.value());
  16. // => true

_.chain(value)

#

创建一个绑定 value 方法的链式lodash对象

参数

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

返回值

(Object): 返回新的 lodash wrapper实例

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36 },
  3. { 'user': 'fred', 'age': 40 },
  4. { 'user': 'pebbles', 'age': 1 }
  5. ];
  6. var youngest = _.chain(users)
  7. .sortBy('age')
  8. .map(function(chr) {
  9. return chr.user + ' is ' + chr.age;
  10. })
  11. .first()
  12. .value();
  13. // => '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.

拦截器,你可以在链条当中插它一下,可以对数据进行处理,可以返回值也可以不返回值,也可以仅仅是打印一下中间的过程,拿tap来debug 链式反应的过程是不错的选择。

参数

  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. _([1, 2, 3])
  2. .tap(function(array) {
  3. array.pop();
  4. })
  5. .reverse()
  6. .value();
  7. // => [2, 1]

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

#

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

tap非常相似,但是必须有返回值

参数

  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.

例子

  1. _(' abc ')
  2. .chain()
  3. .trim()
  4. .thru(function(value) {
  5. return [value];
  6. })
  7. .value();
  8. // => ['abc']

_.prototype.chain()

#

Enables explicit method chaining on the wrapper object.

包装一个对象,使其具有显式的链式的方法

返回值

(Object): 返回一个新的 lodash包装实例对象.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36 },
  3. { 'user': 'fred', 'age': 40 }
  4. ];
  5. // without explicit chaining
  6. _(users).first();
  7. // => { 'user': 'barney', 'age': 36 }
  8. // with explicit chaining
  9. _(users).chain()
  10. .first()
  11. .pick('user')
  12. .value();
  13. // => { 'user': 'barney' }

_.prototype.commit()

#

Executes the chained sequence and returns the wrapped result.

执行链接序列并返回链式包装的结果。

返回值

(Object): Returns the new lodash wrapper instance.

例子

  1. var array = [1, 2];
  2. var wrapped = _(array).push(3);
  3. console.log(array);
  4. // => [1, 2]
  5. wrapped = wrapped.commit();
  6. console.log(array);
  7. // => [1, 2, 3]
  8. wrapped.last();
  9. // => 3
  10. console.log(array);
  11. // => [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.

例子

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

_.prototype.plant()

#

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

克隆一个已有的操作链

返回值

(Object): Returns the new lodash wrapper instance.

例子

  1. var array = [1, 2];
  2. var wrapped = _(array).map(function(value) {
  3. return Math.pow(value, 2);
  4. });
  5. var other = [3, 4];
  6. var otherWrapped = wrapped.plant(other);
  7. otherWrapped.value();
  8. // => [9, 16]
  9. wrapped.value();
  10. // => [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: 此方法会改变被操作的数组.

返回值

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

例子

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

_.prototype.toString()

#

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

将unwrapped 的值转为字符串

返回值

(string): Returns the coerced string value.

例子

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

_.prototype.value()

#

Executes the chained sequence to extract the unwrapped value.

执行操作连,提取出unwrapped 的值

别名(Aliases)

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

返回值

(*): Returns the resolved unwrapped value.

例子

  1. _([1, 2, 3]).value();
  2. // => [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.

根据所给的索引值indexes和键值keys,获取collection里边的元素

参数

  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): 返回挑选出来的元素.

例子

  1. _.at(['a', 'b', 'c'], [0, 2]);
  2. // => ['a', 'c']
  3. _.at(['barney', 'fred', 'pebbles'], 0, 2);
  4. // => ['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.

按照条件 iteratee计算每个元素的个数,返回一个对象,key为元素,value为count的个数

参数

  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.

例子

  1. _.countBy([4.3, 6.1, 6.4], function(n) {
  2. return Math.floor(n);
  3. });
  4. // => { '4': 1, '6': 2 }
  5. _.countBy([4.3, 6.1, 6.4], function(n) {
  6. return this.floor(n);
  7. }, Math);
  8. // => { '4': 1, '6': 2 }
  9. _.countBy(['one', 'two', 'three'], 'length');
  10. // => { '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.

例子

  1. _.every([true, 1, null, 'yes'], Boolean);
  2. // => false
  3. var users = [
  4. { 'user': 'barney', 'active': false },
  5. { 'user': 'fred', 'active': false }
  6. ];
  7. // using the `_.matches` callback shorthand
  8. _.every(users, { 'user': 'barney', 'active': false });
  9. // => false
  10. // using the `_.matchesProperty` callback shorthand
  11. _.every(users, 'active', false);
  12. // => true
  13. // using the `_.property` callback shorthand
  14. _.every(users, 'active');
  15. // => 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.

例子

  1. _.filter([4, 5, 6], function(n) {
  2. return n % 2 == 0;
  3. });
  4. // => [4, 6]
  5. var users = [
  6. { 'user': 'barney', 'age': 36, 'active': true },
  7. { 'user': 'fred', 'age': 40, 'active': false }
  8. ];
  9. // using the `_.matches` callback shorthand
  10. _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
  11. // => ['barney']
  12. // using the `_.matchesProperty` callback shorthand
  13. _.pluck(_.filter(users, 'active', false), 'user');
  14. // => ['fred']
  15. // using the `_.property` callback shorthand
  16. _.pluck(_.filter(users, 'active'), 'user');
  17. // => ['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.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36, 'active': true },
  3. { 'user': 'fred', 'age': 40, 'active': false },
  4. { 'user': 'pebbles', 'age': 1, 'active': true }
  5. ];
  6. _.result(_.find(users, function(chr) {
  7. return chr.age < 40;
  8. }), 'user');
  9. // => 'barney'
  10. // using the `_.matches` callback shorthand
  11. _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
  12. // => 'pebbles'
  13. // using the `_.matchesProperty` callback shorthand
  14. _.result(_.find(users, 'active', false), 'user');
  15. // => 'fred'
  16. // using the `_.property` callback shorthand
  17. _.result(_.find(users, 'active'), 'user');
  18. // => '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.

例子

  1. _.findLast([1, 2, 3, 4], function(n) {
  2. return n % 2 == 1;
  3. });
  4. // => 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.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36, 'active': true },
  3. { 'user': 'fred', 'age': 40, 'active': false }
  4. ];
  5. _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
  6. // => 'barney'
  7. _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
  8. // => '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. _([1, 2]).forEach(function(n) {
  2. console.log(n);
  3. }).value();
  4. // => logs each value from left to right and returns the array
  5. _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
  6. console.log(n, key);
  7. });
  8. // => 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. _([1, 2]).forEachRight(function(n) {
  2. console.log(n);
  3. }).value();
  4. // => 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.

例子

  1. _.groupBy([4.2, 6.1, 6.4], function(n) {
  2. return Math.floor(n);
  3. });
  4. // => { '4': [4.2], '6': [6.1, 6.4] }
  5. _.groupBy([4.2, 6.1, 6.4], function(n) {
  6. return this.floor(n);
  7. }, Math);
  8. // => { '4': [4.2], '6': [6.1, 6.4] }
  9. // using the `_.property` callback shorthand
  10. _.groupBy(['one', 'two', 'three'], 'length');
  11. // => { '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.

例子

  1. _.includes([1, 2, 3], 1);
  2. // => true
  3. _.includes([1, 2, 3], 1, 2);
  4. // => false
  5. _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
  6. // => true
  7. _.includes('pebbles', 'eb');
  8. // => 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.

例子

  1. var keyData = [
  2. { 'dir': 'left', 'code': 97 },
  3. { 'dir': 'right', 'code': 100 }
  4. ];
  5. _.indexBy(keyData, 'dir');
  6. // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
  7. _.indexBy(keyData, function(object) {
  8. return String.fromCharCode(object.code);
  9. });
  10. // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  11. _.indexBy(keyData, function(object) {
  12. return this.fromCharCode(object.code);
  13. }, String);
  14. // => { '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.

例子

  1. _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  2. // => [[1, 5, 7], [1, 2, 3]]
  3. _.invoke([123, 456], String.prototype.split, '');
  4. // => [['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.

例子

  1. function timesThree(n) {
  2. return n * 3;
  3. }
  4. _.map([1, 2], timesThree);
  5. // => [3, 6]
  6. _.map({ 'a': 1, 'b': 2 }, timesThree);
  7. // => [3, 6] (iteration order is not guaranteed)
  8. var users = [
  9. { 'user': 'barney' },
  10. { 'user': 'fred' }
  11. ];
  12. // using the `_.property` callback shorthand
  13. _.map(users, 'user');
  14. // => ['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.

例子

  1. _.partition([1, 2, 3], function(n) {
  2. return n % 2;
  3. });
  4. // => [[1, 3], [2]]
  5. _.partition([1.2, 2.3, 3.4], function(n) {
  6. return this.floor(n) % 2;
  7. }, Math);
  8. // => [[1.2, 3.4], [2.3]]
  9. var users = [
  10. { 'user': 'barney', 'age': 36, 'active': false },
  11. { 'user': 'fred', 'age': 40, 'active': true },
  12. { 'user': 'pebbles', 'age': 1, 'active': false }
  13. ];
  14. var mapper = function(array) {
  15. return _.pluck(array, 'user');
  16. };
  17. // using the `_.matches` callback shorthand
  18. _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
  19. // => [['pebbles'], ['barney', 'fred']]
  20. // using the `_.matchesProperty` callback shorthand
  21. _.map(_.partition(users, 'active', false), mapper);
  22. // => [['barney', 'pebbles'], ['fred']]
  23. // using the `_.property` callback shorthand
  24. _.map(_.partition(users, 'active'), mapper);
  25. // => [['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.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36 },
  3. { 'user': 'fred', 'age': 40 }
  4. ];
  5. _.pluck(users, 'user');
  6. // => ['barney', 'fred']
  7. var userIndex = _.indexBy(users, 'user');
  8. _.pluck(userIndex, 'age');
  9. // => [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.

例子

  1. _.reduce([1, 2], function(total, n) {
  2. return total + n;
  3. });
  4. // => 3
  5. _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
  6. result[key] = n * 3;
  7. return result;
  8. }, {});
  9. // => { '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.

例子

  1. var array = [[0, 1], [2, 3], [4, 5]];
  2. _.reduceRight(array, function(flattened, other) {
  3. return flattened.concat(other);
  4. }, []);
  5. // => [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.

例子

  1. _.reject([1, 2, 3, 4], function(n) {
  2. return n % 2 == 0;
  3. });
  4. // => [1, 3]
  5. var users = [
  6. { 'user': 'barney', 'age': 36, 'active': false },
  7. { 'user': 'fred', 'age': 40, 'active': true }
  8. ];
  9. // using the `_.matches` callback shorthand
  10. _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
  11. // => ['barney']
  12. // using the `_.matchesProperty` callback shorthand
  13. _.pluck(_.reject(users, 'active', false), 'user');
  14. // => ['fred']
  15. // using the `_.property` callback shorthand
  16. _.pluck(_.reject(users, 'active'), 'user');
  17. // => ['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).

例子

  1. _.sample([1, 2, 3, 4]);
  2. // => 2
  3. _.sample([1, 2, 3, 4], 2);
  4. // => [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.

例子

  1. _.shuffle([1, 2, 3, 4]);
  2. // => [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.

例子

  1. _.size([1, 2, 3]);
  2. // => 3
  3. _.size({ 'a': 1, 'b': 2 });
  4. // => 2
  5. _.size('pebbles');
  6. // => 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.

例子

  1. _.some([null, 0, 'yes', false], Boolean);
  2. // => true
  3. var users = [
  4. { 'user': 'barney', 'active': true },
  5. { 'user': 'fred', 'active': false }
  6. ];
  7. // using the `_.matches` callback shorthand
  8. _.some(users, { 'user': 'barney', 'active': false });
  9. // => false
  10. // using the `_.matchesProperty` callback shorthand
  11. _.some(users, 'active', false);
  12. // => true
  13. // using the `_.property` callback shorthand
  14. _.some(users, 'active');
  15. // => 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.

例子

  1. _.sortBy([1, 2, 3], function(n) {
  2. return Math.sin(n);
  3. });
  4. // => [3, 1, 2]
  5. _.sortBy([1, 2, 3], function(n) {
  6. return this.sin(n);
  7. }, Math);
  8. // => [3, 1, 2]
  9. var users = [
  10. { 'user': 'fred' },
  11. { 'user': 'pebbles' },
  12. { 'user': 'barney' }
  13. ];
  14. // using the `_.property` callback shorthand
  15. _.pluck(_.sortBy(users, 'user'), 'user');
  16. // => ['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.

例子

  1. var users = [
  2. { 'user': 'fred', 'age': 48 },
  3. { 'user': 'barney', 'age': 36 },
  4. { 'user': 'fred', 'age': 42 },
  5. { 'user': 'barney', 'age': 34 }
  6. ];
  7. _.map(_.sortByAll(users, ['user', 'age']), _.values);
  8. // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
  9. _.map(_.sortByAll(users, 'user', function(chr) {
  10. return Math.floor(chr.age / 10);
  11. }), _.values);
  12. // => [['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.

例子

  1. var users = [
  2. { 'user': 'fred', 'age': 48 },
  3. { 'user': 'barney', 'age': 34 },
  4. { 'user': 'fred', 'age': 42 },
  5. { 'user': 'barney', 'age': 36 }
  6. ];
  7. // sort by `user` in ascending order and by `age` in descending order
  8. _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
  9. // => [['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.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
  3. { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
  4. ];
  5. _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
  6. // => ['barney']
  7. _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
  8. // => ['fred']

“Date” Methods

_.now

#

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

例子

  1. _.defer(function(stamp) {
  2. console.log(_.now() - stamp);
  3. }, _.now());
  4. // => 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.

例子

  1. var saves = ['profile', 'settings'];
  2. var done = _.after(saves.length, function() {
  3. console.log('done saving!');
  4. });
  5. _.forEach(saves, function(type) {
  6. asyncSave({ 'type': type, 'complete': done });
  7. });
  8. // => 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.

例子

  1. _.map(['6', '8', '10'], _.ary(parseInt, 1));
  2. // => [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.

例子

  1. jQuery('#add').on('click', _.before(5, addContactToList));
  2. // => 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.

例子

  1. var greet = function(greeting, punctuation) {
  2. return greeting + ' ' + this.user + punctuation;
  3. };
  4. var object = { 'user': 'fred' };
  5. var bound = _.bind(greet, object, 'hi');
  6. bound('!');
  7. // => 'hi fred!'
  8. // using placeholders
  9. var bound = _.bind(greet, object, _, '!');
  10. bound('hi');
  11. // => '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.

例子

  1. var view = {
  2. 'label': 'docs',
  3. 'onClick': function() {
  4. console.log('clicked ' + this.label);
  5. }
  6. };
  7. _.bindAll(view);
  8. jQuery('#docs').on('click', view.onClick);
  9. // => 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.

例子

  1. var object = {
  2. 'user': 'fred',
  3. 'greet': function(greeting, punctuation) {
  4. return greeting + ' ' + this.user + punctuation;
  5. }
  6. };
  7. var bound = _.bindKey(object, 'greet', 'hi');
  8. bound('!');
  9. // => 'hi fred!'
  10. object.greet = function(greeting, punctuation) {
  11. return greeting + 'ya ' + this.user + punctuation;
  12. };
  13. bound('!');
  14. // => 'hiya fred!'
  15. // using placeholders
  16. var bound = _.bindKey(object, 'greet', _, '!');
  17. bound('hi');
  18. // => '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.

例子

  1. var abc = function(a, b, c) {
  2. return [a, b, c];
  3. };
  4. var curried = _.curry(abc);
  5. curried(1)(2)(3);
  6. // => [1, 2, 3]
  7. curried(1, 2)(3);
  8. // => [1, 2, 3]
  9. curried(1, 2, 3);
  10. // => [1, 2, 3]
  11. // using placeholders
  12. curried(1)(_, 3)(2);
  13. // => [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.

例子

  1. var abc = function(a, b, c) {
  2. return [a, b, c];
  3. };
  4. var curried = _.curryRight(abc);
  5. curried(3)(2)(1);
  6. // => [1, 2, 3]
  7. curried(2, 3)(1);
  8. // => [1, 2, 3]
  9. curried(1, 2, 3);
  10. // => [1, 2, 3]
  11. // using placeholders
  12. curried(3)(1, _)(2);
  13. // => [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.

例子

  1. // avoid costly calculations while the window size is in flux
  2. jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  3. // invoke `sendMail` when the click event is fired, debouncing subsequent calls
  4. jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
  5. 'leading': true,
  6. 'trailing': false
  7. }));
  8. // ensure `batchLog` is invoked once after 1 second of debounced calls
  9. var source = new EventSource('/stream');
  10. jQuery(source).on('message', _.debounce(batchLog, 250, {
  11. 'maxWait': 1000
  12. }));
  13. // cancel a debounced call
  14. var todoChanges = _.debounce(batchLog, 1000);
  15. Object.observe(models.todo, todoChanges);
  16. Object.observe(models, function(changes) {
  17. if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
  18. todoChanges.cancel();
  19. }
  20. }, ['delete']);
  21. // ...at some point `models.todo` is changed
  22. models.todo.completed = true;
  23. // ...before 1 second has passed `models.todo` is deleted
  24. // which cancels the debounced `todoChanges` call
  25. 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.

例子

  1. _.defer(function(text) {
  2. console.log(text);
  3. }, 'deferred');
  4. // 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.

例子

  1. _.delay(function(text) {
  2. console.log(text);
  3. }, 1000, 'later');
  4. // => 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.

例子

  1. function square(n) {
  2. return n * n;
  3. }
  4. var addSquare = _.flow(_.add, square);
  5. addSquare(1, 2);
  6. // => 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.

例子

  1. function square(n) {
  2. return n * n;
  3. }
  4. var addSquare = _.flowRight(square, _.add);
  5. addSquare(1, 2);
  6. // => 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.

例子

  1. var upperCase = _.memoize(function(string) {
  2. return string.toUpperCase();
  3. });
  4. upperCase('fred');
  5. // => 'FRED'
  6. // modifying the result cache
  7. upperCase.cache.set('fred', 'BARNEY');
  8. upperCase('fred');
  9. // => 'BARNEY'
  10. // replacing `_.memoize.Cache`
  11. var object = { 'user': 'fred' };
  12. var other = { 'user': 'barney' };
  13. var identity = _.memoize(_.identity);
  14. identity(object);
  15. // => { 'user': 'fred' }
  16. identity(other);
  17. // => { 'user': 'fred' }
  18. _.memoize.Cache = WeakMap;
  19. var identity = _.memoize(_.identity);
  20. identity(object);
  21. // => { 'user': 'fred' }
  22. identity(other);
  23. // => { '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.

例子

  1. function doubled(n) {
  2. return n * 2;
  3. }
  4. function square(n) {
  5. return n * n;
  6. }
  7. var modded = _.modArgs(function(x, y) {
  8. return [x, y];
  9. }, square, doubled);
  10. modded(1, 2);
  11. // => [1, 4]
  12. modded(5, 10);
  13. // => [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.

例子

  1. function isEven(n) {
  2. return n % 2 == 0;
  3. }
  4. _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
  5. // => [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.

例子

  1. var initialize = _.once(createApplication);
  2. initialize();
  3. initialize();
  4. // `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.

例子

  1. var greet = function(greeting, name) {
  2. return greeting + ' ' + name;
  3. };
  4. var sayHelloTo = _.partial(greet, 'hello');
  5. sayHelloTo('fred');
  6. // => 'hello fred'
  7. // using placeholders
  8. var greetFred = _.partial(greet, _, 'fred');
  9. greetFred('hi');
  10. // => '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.

例子

  1. var greet = function(greeting, name) {
  2. return greeting + ' ' + name;
  3. };
  4. var greetFred = _.partialRight(greet, 'fred');
  5. greetFred('hi');
  6. // => 'hi fred'
  7. // using placeholders
  8. var sayHelloTo = _.partialRight(greet, 'hello', _);
  9. sayHelloTo('fred');
  10. // => '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.

例子

  1. var rearged = _.rearg(function(a, b, c) {
  2. return [a, b, c];
  3. }, 2, 0, 1);
  4. rearged('b', 'c', 'a')
  5. // => ['a', 'b', 'c']
  6. var map = _.rearg(_.map, [1, 0]);
  7. map(function(n) {
  8. return n * 3;
  9. }, [1, 2, 3]);
  10. // => [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.

例子

  1. var say = _.restParam(function(what, names) {
  2. return what + ' ' + _.initial(names).join(', ') +
  3. (_.size(names) > 1 ? ', & ' : '') + _.last(names);
  4. });
  5. say('hello', 'fred', 'barney', 'pebbles');
  6. // => '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.

例子

  1. var say = _.spread(function(who, what) {
  2. return who + ' says ' + what;
  3. });
  4. say(['fred', 'hello']);
  5. // => 'fred says hello'
  6. // with a Promise
  7. var numbers = Promise.all([
  8. Promise.resolve(40),
  9. Promise.resolve(36)
  10. ]);
  11. numbers.then(_.spread(function(x, y) {
  12. return x + y;
  13. }));
  14. // => 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.

例子

  1. // avoid excessively updating the position while scrolling
  2. jQuery(window).on('scroll', _.throttle(updatePosition, 100));
  3. // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
  4. jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  5. 'trailing': false
  6. }));
  7. // cancel a trailing throttled call
  8. 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.

例子

  1. var p = _.wrap(_.escape, function(func, text) {
  2. return '<p>' + func(text) + '</p>';
  3. });
  4. p('fred, barney, & pebbles');
  5. // => '<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.

例子

  1. var users = [
  2. { 'user': 'barney' },
  3. { 'user': 'fred' }
  4. ];
  5. var shallow = _.clone(users);
  6. shallow[0] === users[0];
  7. // => true
  8. var deep = _.clone(users, true);
  9. deep[0] === users[0];
  10. // => false
  11. // using a customizer callback
  12. var el = _.clone(document.body, function(value) {
  13. if (_.isElement(value)) {
  14. return value.cloneNode(false);
  15. }
  16. });
  17. el === document.body
  18. // => false
  19. el.nodeName
  20. // => BODY
  21. el.childNodes.length;
  22. // => 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.

例子

  1. var users = [
  2. { 'user': 'barney' },
  3. { 'user': 'fred' }
  4. ];
  5. var deep = _.cloneDeep(users);
  6. deep[0] === users[0];
  7. // => false
  8. // using a customizer callback
  9. var el = _.cloneDeep(document.body, function(value) {
  10. if (_.isElement(value)) {
  11. return value.cloneNode(true);
  12. }
  13. });
  14. el === document.body
  15. // => false
  16. el.nodeName
  17. // => BODY
  18. el.childNodes.length;
  19. // => 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.

例子

  1. _.gt(3, 1);
  2. // => true
  3. _.gt(3, 3);
  4. // => false
  5. _.gt(1, 3);
  6. // => 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.

例子

  1. _.gte(3, 1);
  2. // => true
  3. _.gte(3, 3);
  4. // => true
  5. _.gte(1, 3);
  6. // => 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.

例子

  1. _.isArguments(function() { return arguments; }());
  2. // => true
  3. _.isArguments([1, 2, 3]);
  4. // => 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.

例子

  1. _.isArray([1, 2, 3]);
  2. // => true
  3. _.isArray(function() { return arguments; }());
  4. // => 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.

例子

  1. _.isBoolean(false);
  2. // => true
  3. _.isBoolean(null);
  4. // => 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.

例子

  1. _.isDate(new Date);
  2. // => true
  3. _.isDate('Mon April 23 2012');
  4. // => 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.

例子

  1. _.isElement(document.body);
  2. // => true
  3. _.isElement('<body>');
  4. // => 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.

例子

  1. _.isEmpty(null);
  2. // => true
  3. _.isEmpty(true);
  4. // => true
  5. _.isEmpty(1);
  6. // => true
  7. _.isEmpty([1, 2, 3]);
  8. // => false
  9. _.isEmpty({ 'a': 1 });
  10. // => 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.

例子

  1. var object = { 'user': 'fred' };
  2. var other = { 'user': 'fred' };
  3. object == other;
  4. // => false
  5. _.isEqual(object, other);
  6. // => true
  7. // using a customizer callback
  8. var array = ['hello', 'goodbye'];
  9. var other = ['hi', 'goodbye'];
  10. _.isEqual(array, other, function(value, other) {
  11. if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
  12. return true;
  13. }
  14. });
  15. // => 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.

例子

  1. _.isError(new Error);
  2. // => true
  3. _.isError(Error);
  4. // => 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.

例子

  1. _.isFinite(10);
  2. // => true
  3. _.isFinite('10');
  4. // => false
  5. _.isFinite(true);
  6. // => false
  7. _.isFinite(Object(10));
  8. // => false
  9. _.isFinite(Infinity);
  10. // => 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.

例子

  1. _.isFunction(_);
  2. // => true
  3. _.isFunction(/abc/);
  4. // => 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.

例子

  1. var object = { 'user': 'fred', 'age': 40 };
  2. _.isMatch(object, { 'age': 40 });
  3. // => true
  4. _.isMatch(object, { 'age': 36 });
  5. // => false
  6. // using a customizer callback
  7. var object = { 'greeting': 'hello' };
  8. var source = { 'greeting': 'hi' };
  9. _.isMatch(object, source, function(value, other) {
  10. return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
  11. });
  12. // => 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.

例子

  1. _.isNaN(NaN);
  2. // => true
  3. _.isNaN(new Number(NaN));
  4. // => true
  5. isNaN(undefined);
  6. // => true
  7. _.isNaN(undefined);
  8. // => 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.

例子

  1. _.isNative(Array.prototype.push);
  2. // => true
  3. _.isNative(_);
  4. // => false

_.isNull(value)

#

Checks if value is null.

参数

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

返回值

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

例子

  1. _.isNull(null);
  2. // => true
  3. _.isNull(void 0);
  4. // => 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.

例子

  1. _.isNumber(8.4);
  2. // => true
  3. _.isNumber(NaN);
  4. // => true
  5. _.isNumber('8.4');
  6. // => 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.

例子

  1. _.isObject({});
  2. // => true
  3. _.isObject([1, 2, 3]);
  4. // => true
  5. _.isObject(1);
  6. // => 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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. }
  4. _.isPlainObject(new Foo);
  5. // => false
  6. _.isPlainObject([1, 2, 3]);
  7. // => false
  8. _.isPlainObject({ 'x': 0, 'y': 0 });
  9. // => true
  10. _.isPlainObject(Object.create(null));
  11. // => 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.

例子

  1. _.isRegExp(/abc/);
  2. // => true
  3. _.isRegExp('/abc/');
  4. // => 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.

例子

  1. _.isString('abc');
  2. // => true
  3. _.isString(1);
  4. // => 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.

例子

  1. _.isTypedArray(new Uint8Array);
  2. // => true
  3. _.isTypedArray([]);
  4. // => false

_.isUndefined(value)

#

Checks if value is undefined.

参数

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

返回值

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

例子

  1. _.isUndefined(void 0);
  2. // => true
  3. _.isUndefined(null);
  4. // => 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.

例子

  1. _.lt(1, 3);
  2. // => true
  3. _.lt(3, 3);
  4. // => false
  5. _.lt(3, 1);
  6. // => 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.

例子

  1. _.lte(1, 3);
  2. // => true
  3. _.lte(3, 3);
  4. // => true
  5. _.lte(3, 1);
  6. // => false

_.toArray(value)

#

Converts value to an array.

参数

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

返回值

(Array): Returns the converted array.

例子

  1. (function() {
  2. return _.toArray(arguments).slice(1);
  3. }(1, 2, 3));
  4. // => [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.

例子

  1. function Foo() {
  2. this.b = 2;
  3. }
  4. Foo.prototype.c = 3;
  5. _.assign({ 'a': 1 }, new Foo);
  6. // => { 'a': 1, 'b': 2 }
  7. _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  8. // => { '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.

例子

  1. _.add(6, 4);
  2. // => 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.

例子

  1. _.ceil(4.006);
  2. // => 5
  3. _.ceil(6.004, 2);
  4. // => 6.01
  5. _.ceil(6040, -2);
  6. // => 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.

例子

  1. _.floor(4.006);
  2. // => 4
  3. _.floor(0.046, 2);
  4. // => 0.04
  5. _.floor(4060, -2);
  6. // => 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.

例子

  1. _.max([4, 2, 8, 6]);
  2. // => 8
  3. _.max([]);
  4. // => -Infinity
  5. var users = [
  6. { 'user': 'barney', 'age': 36 },
  7. { 'user': 'fred', 'age': 40 }
  8. ];
  9. _.max(users, function(chr) {
  10. return chr.age;
  11. });
  12. // => { 'user': 'fred', 'age': 40 }
  13. // using the `_.property` callback shorthand
  14. _.max(users, 'age');
  15. // => { '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.

例子

  1. _.min([4, 2, 8, 6]);
  2. // => 2
  3. _.min([]);
  4. // => Infinity
  5. var users = [
  6. { 'user': 'barney', 'age': 36 },
  7. { 'user': 'fred', 'age': 40 }
  8. ];
  9. _.min(users, function(chr) {
  10. return chr.age;
  11. });
  12. // => { 'user': 'barney', 'age': 36 }
  13. // using the `_.property` callback shorthand
  14. _.min(users, 'age');
  15. // => { '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.

例子

  1. _.round(4.006);
  2. // => 4
  3. _.round(4.006, 2);
  4. // => 4.01
  5. _.round(4060, -2);
  6. // => 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.

例子

  1. _.sum([4, 6]);
  2. // => 10
  3. _.sum({ 'a': 4, 'b': 6 });
  4. // => 10
  5. var objects = [
  6. { 'n': 4 },
  7. { 'n': 6 }
  8. ];
  9. _.sum(objects, function(object) {
  10. return object.n;
  11. });
  12. // => 10
  13. // using the `_.property` callback shorthand
  14. _.sum(objects, 'n');
  15. // => 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.

例子

  1. _.inRange(3, 2, 4);
  2. // => true
  3. _.inRange(4, 8);
  4. // => true
  5. _.inRange(4, 2);
  6. // => false
  7. _.inRange(2, 2);
  8. // => false
  9. _.inRange(1.2, 2);
  10. // => true
  11. _.inRange(5.2, 4);
  12. // => 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.

例子

  1. _.random(0, 5);
  2. // => an integer between 0 and 5
  3. _.random(5);
  4. // => also an integer between 0 and 5
  5. _.random(5, true);
  6. // => a floating-point number between 0 and 5
  7. _.random(1.2, 5.2);
  8. // => 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.

例子

  1. _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
  2. // => { 'user': 'fred', 'age': 40 }
  3. // using a customizer callback
  4. var defaults = _.partialRight(_.assign, function(value, other) {
  5. return _.isUndefined(value) ? other : value;
  6. });
  7. defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
  8. // => { '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.

例子

  1. function Shape() {
  2. this.x = 0;
  3. this.y = 0;
  4. }
  5. function Circle() {
  6. Shape.call(this);
  7. }
  8. Circle.prototype = _.create(Shape.prototype, {
  9. 'constructor': Circle
  10. });
  11. var circle = new Circle;
  12. circle instanceof Circle;
  13. // => true
  14. circle instanceof Shape;
  15. // => 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.

例子

  1. _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
  2. // => { '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.

例子

  1. _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
  2. // => { '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.

例子

  1. var users = {
  2. 'barney': { 'age': 36, 'active': true },
  3. 'fred': { 'age': 40, 'active': false },
  4. 'pebbles': { 'age': 1, 'active': true }
  5. };
  6. _.findKey(users, function(chr) {
  7. return chr.age < 40;
  8. });
  9. // => 'barney' (iteration order is not guaranteed)
  10. // using the `_.matches` callback shorthand
  11. _.findKey(users, { 'age': 1, 'active': true });
  12. // => 'pebbles'
  13. // using the `_.matchesProperty` callback shorthand
  14. _.findKey(users, 'active', false);
  15. // => 'fred'
  16. // using the `_.property` callback shorthand
  17. _.findKey(users, 'active');
  18. // => '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.

例子

  1. var users = {
  2. 'barney': { 'age': 36, 'active': true },
  3. 'fred': { 'age': 40, 'active': false },
  4. 'pebbles': { 'age': 1, 'active': true }
  5. };
  6. _.findLastKey(users, function(chr) {
  7. return chr.age < 40;
  8. });
  9. // => returns `pebbles` assuming `_.findKey` returns `barney`
  10. // using the `_.matches` callback shorthand
  11. _.findLastKey(users, { 'age': 36, 'active': true });
  12. // => 'barney'
  13. // using the `_.matchesProperty` callback shorthand
  14. _.findLastKey(users, 'active', false);
  15. // => 'fred'
  16. // using the `_.property` callback shorthand
  17. _.findLastKey(users, 'active');
  18. // => '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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.forIn(new Foo, function(value, key) {
  7. console.log(key);
  8. });
  9. // => 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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.forInRight(new Foo, function(value, key) {
  7. console.log(key);
  8. });
  9. // => 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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.forOwn(new Foo, function(value, key) {
  7. console.log(key);
  8. });
  9. // => 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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.forOwnRight(new Foo, function(value, key) {
  7. console.log(key);
  8. });
  9. // => 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.

例子

  1. _.functions(_);
  2. // => ['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.

例子

  1. var object = { 'a': [{ 'b': { 'c': 3 } }] };
  2. _.get(object, 'a[0].b.c');
  3. // => 3
  4. _.get(object, ['a', '0', 'b', 'c']);
  5. // => 3
  6. _.get(object, 'a.b.c', 'default');
  7. // => '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.

例子

  1. var object = { 'a': { 'b': { 'c': 3 } } };
  2. _.has(object, 'a');
  3. // => true
  4. _.has(object, 'a.b.c');
  5. // => true
  6. _.has(object, ['a', 'b', 'c']);
  7. // => 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.

例子

  1. var object = { 'a': 1, 'b': 2, 'c': 1 };
  2. _.invert(object);
  3. // => { '1': 'c', '2': 'b' }
  4. // with `multiValue`
  5. _.invert(object, true);
  6. // => { '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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.keys(new Foo);
  7. // => ['a', 'b'] (iteration order is not guaranteed)
  8. _.keys('hi');
  9. // => ['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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.keysIn(new Foo);
  7. // => ['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.

例子

  1. _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  2. return key + value;
  3. });
  4. // => { '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.

例子

  1. _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
  2. return n * 3;
  3. });
  4. // => { 'a': 3, 'b': 6 }
  5. var users = {
  6. 'fred': { 'user': 'fred', 'age': 40 },
  7. 'pebbles': { 'user': 'pebbles', 'age': 1 }
  8. };
  9. // using the `_.property` callback shorthand
  10. _.mapValues(users, 'age');
  11. // => { '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.

例子

  1. var users = {
  2. 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
  3. };
  4. var ages = {
  5. 'data': [{ 'age': 36 }, { 'age': 40 }]
  6. };
  7. _.merge(users, ages);
  8. // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
  9. // using a customizer callback
  10. var object = {
  11. 'fruits': ['apple'],
  12. 'vegetables': ['beet']
  13. };
  14. var other = {
  15. 'fruits': ['banana'],
  16. 'vegetables': ['carrot']
  17. };
  18. _.merge(object, other, function(a, b) {
  19. if (_.isArray(a)) {
  20. return a.concat(b);
  21. }
  22. });
  23. // => { '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.

例子

  1. var object = { 'user': 'fred', 'age': 40 };
  2. _.omit(object, 'age');
  3. // => { 'user': 'fred' }
  4. _.omit(object, _.isNumber);
  5. // => { '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.

例子

  1. _.pairs({ 'barney': 36, 'fred': 40 });
  2. // => [['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.

例子

  1. var object = { 'user': 'fred', 'age': 40 };
  2. _.pick(object, 'user');
  3. // => { 'user': 'fred' }
  4. _.pick(object, _.isString);
  5. // => { '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.

例子

  1. var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
  2. _.result(object, 'a[0].b.c1');
  3. // => 3
  4. _.result(object, 'a[0].b.c2');
  5. // => 4
  6. _.result(object, 'a.b.c', 'default');
  7. // => 'default'
  8. _.result(object, 'a.b.c', _.constant('default'));
  9. // => '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.

例子

  1. var object = { 'a': [{ 'b': { 'c': 3 } }] };
  2. _.set(object, 'a[0].b.c', 4);
  3. console.log(object.a[0].b.c);
  4. // => 4
  5. _.set(object, 'x[0].y.z', 5);
  6. console.log(object.x[0].y.z);
  7. // => 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.

例子

  1. _.transform([2, 3, 4], function(result, n) {
  2. result.push(n *= n);
  3. return n % 2 == 0;
  4. });
  5. // => [4, 9]
  6. _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
  7. result[key] = n * 3;
  8. });
  9. // => { '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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.values(new Foo);
  7. // => [1, 2] (iteration order is not guaranteed)
  8. _.values('hi');
  9. // => ['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.

例子

  1. function Foo() {
  2. this.a = 1;
  3. this.b = 2;
  4. }
  5. Foo.prototype.c = 3;
  6. _.valuesIn(new Foo);
  7. // => [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.

例子

  1. _.camelCase('Foo Bar');
  2. // => 'fooBar'
  3. _.camelCase('--foo-bar');
  4. // => 'fooBar'
  5. _.camelCase('__foo_bar__');
  6. // => 'fooBar'

_.capitalize([string=''])

#

Capitalizes the first character of string.

参数

  1. [string=''] (string): The string to capitalize.

返回值

(string): Returns the capitalized string.

例子

  1. _.capitalize('fred');
  2. // => '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.

例子

  1. _.deburr('déjà vu');
  2. // => '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.

例子

  1. _.endsWith('abc', 'c');
  2. // => true
  3. _.endsWith('abc', 'b');
  4. // => false
  5. _.endsWith('abc', 'b', 2);
  6. // => 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.

例子

  1. _.escape('fred, barney, & pebbles');
  2. // => '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.

例子

  1. _.escapeRegExp('[lodash](https://lodash.com/)');
  2. // => '\[lodash\]\(https:\/\/lodash\.com\/\)'

_.kebabCase([string=''])

#

Converts string to kebab case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the kebab cased string.

例子

  1. _.kebabCase('Foo Bar');
  2. // => 'foo-bar'
  3. _.kebabCase('fooBar');
  4. // => 'foo-bar'
  5. _.kebabCase('__foo_bar__');
  6. // => '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.

例子

  1. _.pad('abc', 8);
  2. // => ' abc '
  3. _.pad('abc', 8, '_-');
  4. // => '_-abc_-_'
  5. _.pad('abc', 3);
  6. // => '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.

例子

  1. _.padLeft('abc', 6);
  2. // => ' abc'
  3. _.padLeft('abc', 6, '_-');
  4. // => '_-_abc'
  5. _.padLeft('abc', 3);
  6. // => '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.

例子

  1. _.padRight('abc', 6);
  2. // => 'abc '
  3. _.padRight('abc', 6, '_-');
  4. // => 'abc_-_'
  5. _.padRight('abc', 3);
  6. // => '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.

例子

  1. _.parseInt('08');
  2. // => 8
  3. _.map(['6', '08', '10'], _.parseInt);
  4. // => [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.

例子

  1. _.repeat('*', 3);
  2. // => '***'
  3. _.repeat('abc', 2);
  4. // => 'abcabc'
  5. _.repeat('abc', 0);
  6. // => ''

_.snakeCase([string=''])

#

Converts string to snake case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the snake cased string.

例子

  1. _.snakeCase('Foo Bar');
  2. // => 'foo_bar'
  3. _.snakeCase('fooBar');
  4. // => 'foo_bar'
  5. _.snakeCase('--foo-bar');
  6. // => 'foo_bar'

_.startCase([string=''])

#

Converts string to start case.

参数

  1. [string=''] (string): The string to convert.

返回值

(string): Returns the start cased string.

例子

  1. _.startCase('--foo-bar');
  2. // => 'Foo Bar'
  3. _.startCase('fooBar');
  4. // => 'Foo Bar'
  5. _.startCase('__foo_bar__');
  6. // => '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.

例子

  1. _.startsWith('abc', 'a');
  2. // => true
  3. _.startsWith('abc', 'b');
  4. // => false
  5. _.startsWith('abc', 'b', 1);
  6. // => 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.

例子

  1. // using the "interpolate" delimiter to create a compiled template
  2. var compiled = _.template('hello <%= user %>!');
  3. compiled({ 'user': 'fred' });
  4. // => 'hello fred!'
  5. // using the HTML "escape" delimiter to escape data property values
  6. var compiled = _.template('<b><%- value %></b>');
  7. compiled({ 'value': '<script>' });
  8. // => '<b>&lt;script&gt;</b>'
  9. // using the "evaluate" delimiter to execute JavaScript and generate HTML
  10. var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
  11. compiled({ 'users': ['fred', 'barney'] });
  12. // => '<li>fred</li><li>barney</li>'
  13. // using the internal `print` function in "evaluate" delimiters
  14. var compiled = _.template('<% print("hello " + user); %>!');
  15. compiled({ 'user': 'barney' });
  16. // => 'hello barney!'
  17. // using the ES delimiter as an alternative to the default "interpolate" delimiter
  18. var compiled = _.template('hello ${ user }!');
  19. compiled({ 'user': 'pebbles' });
  20. // => 'hello pebbles!'
  21. // using custom template delimiters
  22. _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
  23. var compiled = _.template('hello {{ user }}!');
  24. compiled({ 'user': 'mustache' });
  25. // => 'hello mustache!'
  26. // using backslashes to treat delimiters as plain text
  27. var compiled = _.template('<%= "\\<%- value %\\>" %>');
  28. compiled({ 'value': 'ignored' });
  29. // => '<%- value %>'
  30. // using the `imports` option to import `jQuery` as `jq`
  31. var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
  32. var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
  33. compiled({ 'users': ['fred', 'barney'] });
  34. // => '<li>fred</li><li>barney</li>'
  35. // using the `sourceURL` option to specify a custom sourceURL for the template
  36. var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
  37. compiled(data);
  38. // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
  39. // using the `variable` option to ensure a with-statement isn't used in the compiled template
  40. var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
  41. compiled.source;
  42. // => function(data) {
  43. // var __t, __p = '';
  44. // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
  45. // return __p;
  46. // }
  47. // using the `source` property to inline compiled templates for meaningful
  48. // line numbers in error messages and a stack trace
  49. fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  50. var JST = {\
  51. "main": ' + _.template(mainText).source + '\
  52. };\
  53. ');

_.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.

例子

  1. _.trim(' abc ');
  2. // => 'abc'
  3. _.trim('-_-abc-_-', '_-');
  4. // => 'abc'
  5. _.map([' foo ', ' bar '], _.trim);
  6. // => ['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.

例子

  1. _.trimLeft(' abc ');
  2. // => 'abc '
  3. _.trimLeft('-_-abc-_-', '_-');
  4. // => '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.

例子

  1. _.trimRight(' abc ');
  2. // => ' abc'
  3. _.trimRight('-_-abc-_-', '_-');
  4. // => '-_-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.

例子

  1. _.trunc('hi-diddly-ho there, neighborino');
  2. // => 'hi-diddly-ho there, neighbo...'
  3. _.trunc('hi-diddly-ho there, neighborino', 24);
  4. // => 'hi-diddly-ho there, n...'
  5. _.trunc('hi-diddly-ho there, neighborino', {
  6. 'length': 24,
  7. 'separator': ' '
  8. });
  9. // => 'hi-diddly-ho there,...'
  10. _.trunc('hi-diddly-ho there, neighborino', {
  11. 'length': 24,
  12. 'separator': /,? +/
  13. });
  14. // => 'hi-diddly-ho there...'
  15. _.trunc('hi-diddly-ho there, neighborino', {
  16. 'omission': ' [...]'
  17. });
  18. // => '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.

例子

  1. _.unescape('fred, barney, &amp; pebbles');
  2. // => '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.

例子

  1. _.words('fred, barney, & pebbles');
  2. // => ['fred', 'barney', 'pebbles']
  3. _.words('fred, barney, & pebbles', /[^, ]+/g);
  4. // => ['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.

例子

  1. // avoid throwing errors for invalid selectors
  2. var elements = _.attempt(function(selector) {
  3. return document.querySelectorAll(selector);
  4. }, '>_>');
  5. if (_.isError(elements)) {
  6. elements = [];
  7. }

_.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.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36 },
  3. { 'user': 'fred', 'age': 40 }
  4. ];
  5. // wrap to create custom callback shorthands
  6. _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
  7. var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
  8. if (!match) {
  9. return callback(func, thisArg);
  10. }
  11. return function(object) {
  12. return match[2] == 'gt'
  13. ? object[match[1]] > match[3]
  14. : object[match[1]] < match[3];
  15. };
  16. });
  17. _.filter(users, 'age__gt36');
  18. // => [{ '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.

例子

  1. var object = { 'user': 'fred' };
  2. var getter = _.constant(object);
  3. getter() === object;
  4. // => true

_.identity(value)

#

This method returns the first argument provided to it.

参数

  1. value (*): Any value.

返回值

(*): Returns value.

例子

  1. var object = { 'user': 'fred' };
  2. _.identity(object) === object;
  3. // => 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.

例子

  1. var users = [
  2. { 'user': 'barney', 'age': 36, 'active': true },
  3. { 'user': 'fred', 'age': 40, 'active': false }
  4. ];
  5. _.filter(users, _.matches({ 'age': 40, 'active': false }));
  6. // => [{ '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.

例子

  1. var users = [
  2. { 'user': 'barney' },
  3. { 'user': 'fred' }
  4. ];
  5. _.find(users, _.matchesProperty('user', 'fred'));
  6. // => { '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.

例子

  1. var objects = [
  2. { 'a': { 'b': { 'c': _.constant(2) } } },
  3. { 'a': { 'b': { 'c': _.constant(1) } } }
  4. ];
  5. _.map(objects, _.method('a.b.c'));
  6. // => [2, 1]
  7. _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
  8. // => [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.

例子

  1. var array = _.times(3, _.constant),
  2. object = { 'a': array, 'b': array, 'c': array };
  3. _.map(['a[2]', 'c[0]'], _.methodOf(object));
  4. // => [2, 0]
  5. _.map([['a', '2'], ['c', '0']], _.methodOf(object));
  6. // => [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.

例子

  1. function vowels(string) {
  2. return _.filter(string, function(v) {
  3. return /[aeiou]/i.test(v);
  4. });
  5. }
  6. _.mixin({ 'vowels': vowels });
  7. _.vowels('fred');
  8. // => ['e']
  9. _('fred').vowels().value();
  10. // => ['e']
  11. _.mixin({ 'vowels': vowels }, { 'chain': false });
  12. _('fred').vowels();
  13. // => ['e']

_.noConflict()

#

Reverts the _ variable to its previous value and returns a reference to the lodash function.

返回值

(Function): Returns the lodash function.

例子

  1. var lodash = _.noConflict();

_.noop()

#

A no-operation function that returns undefined regardless of the arguments it receives.

例子

  1. var object = { 'user': 'fred' };
  2. _.noop(object) === undefined;
  3. // => 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.

例子

  1. var objects = [
  2. { 'a': { 'b': { 'c': 2 } } },
  3. { 'a': { 'b': { 'c': 1 } } }
  4. ];
  5. _.map(objects, _.property('a.b.c'));
  6. // => [2, 1]
  7. _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
  8. // => [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.

例子

  1. var array = [0, 1, 2],
  2. object = { 'a': array, 'b': array, 'c': array };
  3. _.map(['a[2]', 'c[0]'], _.propertyOf(object));
  4. // => [2, 0]
  5. _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
  6. // => [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.

例子

  1. _.range(4);
  2. // => [0, 1, 2, 3]
  3. _.range(1, 5);
  4. // => [1, 2, 3, 4]
  5. _.range(0, 20, 5);
  6. // => [0, 5, 10, 15]
  7. _.range(0, -4, -1);
  8. // => [0, -1, -2, -3]
  9. _.range(1, 4, 0);
  10. // => [1, 1, 1]
  11. _.range(0);
  12. // => []

_.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.

例子

  1. _.mixin({ 'foo': _.constant('foo') });
  2. var lodash = _.runInContext();
  3. lodash.mixin({ 'bar': lodash.constant('bar') });
  4. _.isFunction(_.foo);
  5. // => true
  6. _.isFunction(_.bar);
  7. // => false
  8. lodash.isFunction(lodash.foo);
  9. // => false
  10. lodash.isFunction(lodash.bar);
  11. // => true
  12. // using `context` to mock `Date#getTime` use in `_.now`
  13. var mock = _.runInContext({
  14. 'Date': function() {
  15. return { 'getTime': getTimeMock };
  16. }
  17. });
  18. // or creating a suped-up `defer` in Node.js
  19. 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.

例子

  1. var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
  2. // => [3, 6, 4]
  3. _.times(3, function(n) {
  4. mage.castSpell(n);
  5. });
  6. // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
  7. _.times(3, function(n) {
  8. this.cast(n);
  9. }, mage);
  10. // => 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.

例子

  1. _.uniqueId('contact_');
  2. // => 'contact_104'
  3. _.uniqueId();
  4. // => '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.