没看过前几篇的可以猛戳这里:

underscore.js源码解析(一)

underscore.js源码解析(二)

underscore.js源码解析(三)

underscore.js源码GitHub地址: https://github.com/jashkenas/underscore/blob/master/underscore.js

本文解析的underscore.js版本是1.8.3

 _.pluck

1   _.pluck = function(obj, key) {
2     return _.map(obj, _.property(key));
3   };

 _.pluck的作用就是获取数据对象中的相应属性,然后存在数组当中返回

_.where

1   _.where = function(obj, attrs) {
2     return _.filter(obj, _.matcher(attrs));
3   };

_.where就是遍历数据,然后返回所有满足条件的值,存在数组当中

_.findWhere

1   _.findWhere = function(obj, attrs) {
2     return _.find(obj, _.matcher(attrs));
3   }

_.findWhere和where不同的是只返回第一个满足条件的

_.max

 1   _.max = function(obj, iteratee, context) {
 2     var result = -Infinity, lastComputed = -Infinity,
 3         value, computed;
 4     //如果没有iteratee
 5     if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
 6       obj = isArrayLike(obj) ? obj : _.values(obj);
 7       //循环遍历求出最大值
 8       for (var i = 0, length = obj.length; i < length; i++) {
 9         value = obj[i];
10         if (value != null && value > result) {
11           result = value;
12         }
13       }
14     } else {
15     //有iteratte的情况
16       iteratee = cb(iteratee, context);
17       _.each(obj, function(v, index, list) {
18         //迭代出的最大值结果
19         computed = iteratee(v, index, list);
20         if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
21           result = v;
22           lastComputed = computed;
23         }
24       });
25     }
26     return result;
27   };

获取obj中的最大值

_.min

 1   _.min = function(obj, iteratee, context) {
 2     var result = Infinity, lastComputed = Infinity,
 3         value, computed;
 4     if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
 5       obj = isArrayLike(obj) ? obj : _.values(obj);
 6       for (var i = 0, length = obj.length; i < length; i++) {
 7         value = obj[i];
 8         if (value != null && value < result) {
 9           result = value;
10         }
11       }
12     } else {
13       iteratee = cb(iteratee, context);
14       _.each(obj, function(v, index, list) {
15         computed = iteratee(v, index, list);
16         if (computed < lastComputed || computed === Infinity && result === Infinity) {
17           result = v;
18           lastComputed = computed;
19         }
20       });
21     }
22     return result;
23   };
View Code

相关文章:

  • 2020-03-20
  • 2022-12-23
  • 2021-09-09
  • 2021-06-29
  • 2021-04-23
  • 2021-12-10
  • 2021-07-31
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2021-07-10
  • 2021-11-13
  • 2022-02-01
相关资源
相似解决方案