SoFunction
Updated on 2025-04-07

angular forEach method traversal source code interpretation

The forEach() method is provided in angular for traversing objects or arrays for your reference. The specific content is as follows

function forEach(obj, iterator, context) {
 var key, length;
 if (obj) {
  if (isFunction(obj)) {
   for (key in obj) {
    // Need to check if hasOwnProperty exists,
    // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
    if (key != 'prototype' && key != 'length' && key != 'name' && (! || (key))) {
     (context, obj[key], key, obj);
    }
   }
  } else if (isArray(obj) || isArrayLike(obj)) {
   var isPrimitive = typeof obj !== 'object';
   for (key = 0, length = ; key < length; key++) {
    if (isPrimitive || key in obj) {
     (context, obj[key], key, obj);
    }
   }
  } else if ( &&  !== forEach) {
    (iterator, context, obj);
  } else if (isBlankObject(obj)) {
   // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
   for (key in obj) {
    (context, obj[key], key, obj);
   }
  } else if (typeof  === 'function') {
   // Slow path for objects inheriting , hasOwnProperty check needed
   for (key in obj) {
    if ((key)) {
     (context, obj[key], key, obj);
    }
   }
  } else {
   // Slow path for objects which do not have a method `hasOwnProperty`
   for (key in obj) {
    if ((obj, key)) {
     (context, obj[key], key, obj);
    }
   }
  }
 }
 return obj;
}

Official description:

The forEach method can traverse an array or object. The function has three parameters: value, key, obj.
1) value value refers to the current value of the object or array element that is traversed.
2) Key is the key or index of the object attribute
3) obj obj is the object or array itself that is traversed

Example:

   var values = {name: 'misko', gender: 'male'};
   var log = [];
   (values, function(value, key) {
    (key + ': ' + value);
   }, log);

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.