underscore.js 源码分析之 _.each() 函数

each _.each(list, iteratee, [context]) Alias: forEach 
遍历list中的全部元素,按顺序用遍历输出每一个元素。若是传递了context参数,则把iteratee绑定到context对象上。每次调用iteratee都会传递三个参数:(element, index, list)。若是list是个JavaScript对象,iteratee的参数是 (value, key, list))。返回list以方便链式调用。javascript

_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...

_.each 源码java

// The cornerstone, an `each` implementation, aka `forEach`.
  // Handles raw objects in addition to array-likes. Treats all
  // sparse array-likes as if they were dense.
  _.each = _.forEach = function(obj, iteratee, context) {
    iteratee = optimizeCb(iteratee, context);
    var i, length;
    if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
        iteratee(obj[i], i, obj);
      }
    } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
        iteratee(obj[keys[i]], keys[i], obj);
      }
    }
    return obj;
  };

分析数组

_.each([1, 2, 3], alert); // _.each()使用方法,其中`alert`能够换成本身写的function

obj[1, 2, 3] , iterateealert , context 没有浏览器

iteratee = optimizeCb(iteratee, context);

首先是调用optimizeCb()函数函数

分析 optimizeCb 源码spa

var optimizeCb = function(func, context, argCount) {
    if (context === void 0) return func;
};

由于context 没有,因此这里直接返回alert , 因此 iteratee 如今是alertprototype

再使用 isArrayLike 判断 传进来的obj是否是数组,判断数组的方法code

//原理就是经过判断它是否具备长度且长度大于0且小于MAX_ARRAY_INDEX
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
    var length = getLength(collection);
    return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  };

由于这里是数组,因此继续对象

// 经过 for 循环来遍历数组里面每个值,传给 iteratee 函数来运行
for (i = 0, length = obj.length; i < length; i++) {
  iteratee(obj[i], i, obj); // 等于 alert(obj[i], i, obj);
}

若是不是数组呢?对象默认是没有length 属性的three

var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
  iteratee(obj[keys[i]], keys[i], obj);
}

使用了_.keys() 函数,下面分析 _keys() 源码

_.keys = function(obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
};

首先使用_.isObject函数判断是否是对象

// Is a given variable an object?
  _.isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
  };

首先判断传进来的参数的类型,而后返回true或者false

注意,经过如下两个例子可知, && 的优先级比 || 的高

console.log(true || false && false) // true
console.log(true || false && true) // true

而后若是浏览器支持 ES5Object.keys 方法,就优先使用

nativeKeys = Object.keys,

不支持就继续遍历循环 对象

var keys = [];
// own enumerable properties
for (var key in obj)
// hasOwnProperty
if (_.has(obj, key)) keys.push(key);

使用了 _.has() 函数,下面解析_.has()函数

// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
  return obj != null && hasOwnProperty.call(obj, key);
};

经过判断 传进来的obj 是否为null 而且调用hasOwnProperty 方法判断该对象是否有该键值

hasOwnProperty   = ObjProto.hasOwnProperty = Object.prototype.hasOwnProperty;

若是有该属性,返回true ,这时回到_.keys() ,该简直pushkeys[]

// IE9如下不能用 for in 来遍历,因此使用collectNonEnumProps()函数来解决问题,暂时能够不看
if (hasEnumBug) collectNonEnumProps(obj, keys);

这时已经把对象转化成数组了,回到_.each() 函数,继续使用for 循环遍历数组 ,把参数传递给alert函数

for (i = 0, length = keys.length; i < length; i++) {
  iteratee(obj[keys[i]], keys[i], obj); //  等于 alert(obj[keys[i]], keys[i], obj);
}

最后再返回obj

整个分析_.each() 函数,相继分析了_.has()_.keys() 函数,大概看了一下underscore.js 的源码,感受不是太难,一个函数一个函数分析就好。

相关文章
相关标签/搜索