写在前面:
1.5.2版本,计24个函数
集合函数能在数组、对象和类数组对象,如arguments、NodeList和类似的数据类型上工作,要避免传递一个不固定length属性的对象
list:待遍历的集合对象
literator:迭代器,即转换函数
memo:初始值
1、each _.each(list, iterator, [context])
遍历list中所有元素,并按顺序遍历输出每个元素。如果传递context,则把iterator绑定到context对象上。调用iterator会传递三个参数(element, index, list),若list为对象,则参数为(value, key, list)
_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...
ps:每次输出的都是值,而不是键
2、map _.map(list, iterator, [context])
通过iterator将list中的每个值映射到一个新的数组中,产生一个新的数组,迭代器参数(value, key, list)
_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
ps:可以将返回值赋值给一个变量使用
3、reduce _.reduce(list, iterator, memo, [context])
别名为inject和foldl,reduce会把list中元素归结为一个单独的数值,reduce的每一步需要由迭代器返回,这个迭代器参数(memo, value, index或key, list)
var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6
4、reduceRight _.reduceRight(list, iterator, memo, [context])
从右侧开始组合元素reduce函数。
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
=> [4, 5, 2, 3, 0, 1]
5、find _.find(list, iterator, [context])
遍历list,返回第一个通过迭代器检测为真值的元素值,如果没有返回undefined,找到后停止遍历,立即返回。
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2
6、filter _.filter(list, iterator, [context])
遍历list,返回所有通过迭代器检测为真值的元素值组成的数组。
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
7、where _.where(list, properties)
遍历list中的每一个值,返回一个包含properties所列出属性所有键值对的新数组
var listOfPlays = [{title: 'aaa',author: "Shakespeare", year: 1611},{title: 'bbb',author: "Shakespeare", year: 1611}];
var arr2=_.findWhere(listOfPlays, {author: "Shakespeare", year: 1611});
=> {{title: 'aaa',author: "Shakespeare", year: 1611},{title: 'bbb',author: "Shakespeare", year: 1611}}
8、findWhere _.findWhere(list, properties)
同where类似,只是返回匹配properties的第一值,若没有匹配到,或者list为空,则返回undefined
var listOfPlays = [{title: 'aaa',author: "Shakespeare", year: 1611},{title: 'bbb',author: "Shakespeare", year: 1611}];
var arr2=_.findWhere(listOfPlays, {author: "Shakespeare", year: 1611});
{title: "aaa", author: "Shakespeare", year: 1611}
9、reject _.reject(list, iterator, [context])
返回list中没有通过迭代器真值检测的元素集合,与filter相反
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]
10、every _.every(list, [iterator], [context])
如果list中的所有元素都通过迭代器的真值检测就返回true
_.every([true, 1, null, 'yes'], _.identity);
=>false
11、some _.some(list, [iterator], [context])
如果list中任何一个元素通过迭代器真值检测就返回true,一旦找到符合条件的元素,就终止遍历
_.some([null, 0, 'yes', false]);
=>true
12、contains _.contains(list, value)
如果list中包含指定value则返回true
_.contains([1, 2, 3], 3);
=>true