写在前面:


1.5.2版本,计24个函数



集合函数能在数组、对象和类数组对象,如arguments、NodeList和类似的数据类型上工作,要避免传递一个不固定length属性的对象




list:

待遍历的集合对象




literator

:迭代器,即转换函数




memo:

初始值




官方下载地址(最新版本)





13、invoke(调用)

_.invoke(list, methodName, [*arguments])



在list的每个元素上都执行methodName方法,任何argument都会在调用methodName方法时传递给他




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


14、pluck(萃取)

_.pluck(list, propertyName)



萃取对象数组中的某个属性值,返回一个数组




var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]


15、max(取最大值)

_.max(list, [iterator], [context])

返回list的最大值,如果传递迭代器,则迭代器将作为list排序的依据

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};


16、min(取最小值)

_.min(list, [iterator], [context])

返回list的最小值,如果传递迭代器,则迭代器将作为list排序的依据

var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2


17、sortBy(排序)

_.sortBy(list, iterator, [context])

返回一个排序后的list拷贝副本,如果存在迭代器,迭代器为list排序依据,迭代器也可以是字符串的属性的名称进行排序(如length—)

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]


18、groupBy(分组)

_.groupBy(list, iterator, [context])

把一个集合分组为多个集合,通过迭代器返回的结果作为分组依据。如果迭代器是一个字符串而不是函数,则将使用迭代器作为各元素的属性名来对比进行分组

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}


19、indexBy(对键名分组)

_.indexBy(list, iterator, [context])

给定一个list,和一个用来返回一个在列表中的每个元素键的iterator函数(或属性名),返回一个每一项索引的对象。和groupBy很像,但当知道键是唯一的时候可以使用indexBy。

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
  "40": {name: 'moe', age: 40},
  "50": {name: 'larry', age: 50},
  "60": {name: 'curly', age: 60}
}


20、countBy(分组返回数量)

_.countBy(list, iterator, [context])

排序一个列表组个一个组,返回各组中的对象的数量的计数。类似groupBy,但是不是返回值,而是返回该组中值得数目

_.countBy([1, 2, 3, 4, 5], function(num) {
  return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}


21、shuffle(洗牌)

_.shuffle(list)

返回一个随机乱序的list副本

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


22、sample(随机样本)

_.sample(list, [n])

从list中随机返回一个样本。若存在n,则返回n个

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

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


23、toArray

_.toArray(list)

把list(任何可以迭代的对象)转换成一个数组,在转换arguments对象时非常有用

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


24、size(长度)

_.size(list)

返回list的长度

_.size({one: 1, two: 2, three: 3});
=> 3



版权声明:本文为u014169707原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u014169707/article/details/21443183