underscore.js 源码分析(二)
_.filter _.where _.findWhere _.reject _.every_.filter
实例
_.filter(list, predicate, [context])遍历 list 值, 返回通过 predicate 函数返回为真的值数组。代码如下:1 | list = [1, 2, 5, 6]; |
源码分析
使用_.filter() 的源码如下所示:1 | _.filter = _.select = function(obj, predicate, context) { |
_.where
实例
_.where(list, propertries)list: 数组propertries : 需要进行检索的键值对(一个对象)遍历 list 中的每一个值, 返回一个数组,这个数组中包含含有 propertries 中属性的所有的键值对。用法:1 | list = [{name: '张宁宁', age: 18}, {name: '张宁宁', age: 70}]; |
1 | function where(list, sObj) { |
_where() 源代码如下所示:1 | _.where = function(obj, attrs) { |
_filter 筛选出 obj 对象中适合函数 _.matches 的键值对儿。_.match() 方法的源码如下所示:1 |
|
对于返回一个函数的这种形式:
1 | function name() { |
_.findWhere
实例
_findWhere(list, properties)遍历整个 list 返回匹配整个 properties 参数所列出的所有键值对儿的第一个值。源码分析
1 | _.findWhere = function(obj, attrs) { |
_.find 函数返回通过第一次获得匹配的对象。_.reject
实例
_.reject(list, predicate, [context])返回 list 列表中没能通过 predicate 检验的数值。1 | function reject() { |
filter 相反。源码分析
1 | _.reject = function(obj, predicate, context) { |
_.negate 函数1 | _.negate = function(predicate) { |
_every
实例
_every(list, [predicate], [context])如果 list 中的元素都通过 predicate 的真值检验就返回为 true代码分析
源码如下:1 | function every(obj, predicate) { |