collections-each4

by shan10213223

JavaScript

var _ = {};
// _.each(collection, iteratee, [context])
// Iterates over a collection of elements (i.e. array or object),
// yielding each in turn to an iteratee function, that is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
// Returns the collection for chaining.
_.each = function (collection, iteratee, context) {
  if (context) {
      iteratee = iteratee.bind(context);
  }
  if (Array.isArray(collection)) {
    for (let i=0; i<collection.length; i++) {
      if (Object.prototype.hasOwnProperty.call(collection, i)) {
        iteratee(collection[i]);
      }
    }
  } else {
  for (let ele in collection) {
    if (Object.prototype.hasOwnProperty.call(collection, ele)) {
      iteratee(collection[ele]);
    } 
  }
  }
  return collection;
  /*if (Array.isArray(collection)) {
    for (let i = 0; i < collection.length; i++) {
      iteratee(collection[i]);
    	//if (Object.prototype.hasOwnProperty.call(collection, collection[i])) {
      //  iteratee(collection[i]);
    	//}
    }
  } else {
    for (let key in collection) {
      iteratee(collection[key]);
    	//if (Object.prototype.hasOwnProperty.call(collection, key)) {
      //  iteratee(collection[key]);
      //}
    }
  }
  return collection;
  */
};

_.each([1,2,3], console.log);

_.each({a:'1', b:'2', c:'3'}, console.log);

let person = {};
person.friends = {
  name1: true,
  name2: false,
  name3: true,
  name4: true
};

_.each(['name4', 'name2'], function(name){
  // this refers to the friends property of the person object
  console.log(this[name]);
}, person.friends);