underscore.js集合、数组相关函数的一些联系与区别…
集合(Collection Functions)
.find()和.filter()的联系和区别
12345678910111213141516171819202122_.find(list, predicate, [context]) 别名: detect_.filter(list, predicate, [context]) 别名: select_.reject(list, predicate, [context])说明:_.find()返回第一个通过predicate真值检测的值,_.filter()则返回全部,而_.reject()则返回所有未通过predicate真值检测的值。eg:_.find([1,4,5], function(item){return item > 1;});// 4_.filter([1,4,5], function(item){return item > 1;});// [4, 5]_.filter([1,4,5], function(item){return item > 4;});// [5]_.reject([1,4,5], function(item){return item > 4;});// [1, 4].findWhere()和.where()的联系和区别
12345678说明:_.findWhere(list, properties): 筛选出第一个含有properties的项_.where(list, properties): 筛选出所有含有properties的项eg:_.findWhere([{a:1,b:2},{b:2,c:3},{b:3,d:4}],{b:2});// {a: 1, b: 2}_.where([{a:1,b:2},{b:2,c:3},{b:3,d:4}],{b:2});// [{a: 1, b: 2}, {b:2, c:3}].invoke()实例、.pluck()实例
123456说明:_.pluck()用于萃取若干对象的某个属性值eg:_.invoke([[1,2,0],[-1,1,0]],"toString");// ["1,2,0", "-1,1,0"]_.pluck([{name:"lucy",age:22}, {name:"Bob",age:23}, {name:"John",age:34}], ["name"]);// ["lucy", "Bob", "John"]_.max()实例
1234567说明:_.max()不仅可以用于获取数组中的最大值,也可以用于获取某属性值取得最大值的对象eg:var arr = [{a:1,b:3},{a:3,b:2},{a:3,b:4}];_.max(arr, function(item){return item.a;});// {a: 3, b: 2}.sortBy()、.groupBy()、.indexBy()、.countBy()的联系与区别
12345678910111213141516171819202122_.sortBy(list, iteratee, [context]): 排序_.groupBy(list, iteratee, [context]):分组_.indexBy(list, iteratee, [context]):分组(键值唯一)_.countBy(list, iteratee, [context]):分组计数eg:_.sortBy([{name:"Bob",age:"34"},{name:"Alice",age:"23"},{name:"Lucy",age:"26"}],"age");// [{name: "Alice", age: "23"},{name: "Lucy", age: "26"},{name: "Bob", age: "34"}]_.groupBy([{a:1,b:3},{a:3,b:4},{a:2,b:2}], function(item){return item.b > 2;});// {false: [{a: 2, b: 2}], true: [{a: 1, b: 3},{a: 3, b: 4}]}_.indexBy([{a:1,b:3,id:"001"},{a:3,b:4,id:"002"},{a:2,b:2,id:"003"}], function(item){return item.id;});// {001: {a: 1, b: 3, id: "001"}, 002: {a: 3, b: 4, id: "002"}, 003: {a: 2, b: 2, id: "003"}}_.countBy([{a:1,b:3},{a:3,b:4},{a:2,b:2}], function(item){return item.b > 2;});// {true: 2, false: 1}
数组(Array Functions)
.first()、.last()、.initial()、.rest()实例
1234567891011121314说明:_.first(n): 前几个_.last(n): 后几个_.initial(n): 除了后几个剩下的_.rest(n): 除了前几个剩下的eg:_.first([1,2,3,4,5],2);// [1, 2]_.last([1,2,3,4,5],2);// [4, 5]_.initial([1,2,3,4,5],2);// [1, 2, 3]_.rest([1,2,3,4,5],2);// [3, 4, 5].union()、.intersection()
12345678说明:_.union(*arrays): 数组并集_.intersection(*arrays): 数组交集eg:_.union([1,3],[3,4]);// [1, 3, 4]_.intersection([1,2],[2,3]);// [2]