Underscore和Lo-Dash中的Collections _.each

_.each

遍历鸠合,对鸠合中的每一个元素实行回调。

API

Lo-Dash

_.forEach(collection [, callback=identity, thisArg])

Aliases

each

Arguments

  1. collection (Array|Object|String): 要遍历的鸠合

  2. [callback=identity] (Function): 每次迭代中挪用的函数

  3. [thisArg] (恣意): 绑定到callbackthis

  4. callback接收三个参数: (value, index|key, collection)

Returns

(Array, Object, String): 返回collection.

Underscore

_.each(list, iterator, [context])

Aliases

forEach

Arguments

  1. list (Array|Object|String): 要遍历的鸠合

  2. iterator (Function): 每次迭代中挪用的函数

  3. [context] (恣意): 绑定到callbackthis

  4. iterator接收三个参数: (element|value, index|key, list)

Returns

(Array, Object, String): 返回undefined.

Note

  • Lo-Dash能够省略回调函数,而Underscore则必需传入

  • Lo-Dash能够经由过程在回调中返回false提前结束迭代

  • Lo-Dash会返回Collection从而许可链式操纵,Underscore的返回值则是undefined

Example

Lo-Dash

_.forEach([1,2,3])
// => 返回[1,2,3]

_([1, 2, 3]).forEach(alert).join(',');
// => alert每一个数字并返回'1,2,3'

_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
// => alert每一个数字value(不保证根据定义的递次实行)

Underscore

_.each([1, 2, 3], alert);
// => alert每一个数字
_.each({one : 1, two : 2, three : 3}, alert);
// => alert每一个数字value(不保证根据定义的递次实行)

Source

Lo-Dash

function forEach(collection, callback, thisArg) {
    var index = -1,
    length = collection ? collection.length : 0;

    callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg);
    if (typeof length == 'number') {
        while (++index < length) {
            if (callback(collection[index], index, collection) === false) {
                break;
            }
        }
    } else {
        forOwn(collection, callback);
    }
    return collection;
}

Underscore

var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (_.has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

Additional

  • obj.length === +obj.length
    +obj: 将obj转换成10进制数,不然返回NaN。因而,上面的推断等价于obj.length && typeof obj.length == 'number'

  • if (iterator.call(context, obj[i], i, obj) === breaker) return;
    breaker是预先定义的空对象({}),Underscore内部用于提前结束轮回的标志,并没有对外公然。别的,由于对象的===比较的是对象地点,所以就算用户在本身的iterator中返回{},上述if依然不成立

  • for in轮回不会遍历non-enumerable属性,因而像ObjecttoString等就不会被迭代

    原文作者:BetaRabbit
    原文地址: https://segmentfault.com/a/1190000004360990
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞