当前位置:Gxlcms > JavaScript > angular forEach方法遍历源码解读

angular forEach方法遍历源码解读

时间:2021-07-01 10:21:17 帮助过:9人阅读

angular中提供了forEach()方法用于遍历对象或数组,供大家参考,具体内容如下

  1. function forEach(obj, iterator, context) {
  2. var key, length;
  3. if (obj) {
  4. if (isFunction(obj)) {
  5. for (key in obj) {
  6. // Need to check if hasOwnProperty exists,
  7. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  8. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  9. iterator.call(context, obj[key], key, obj);
  10. }
  11. }
  12. } else if (isArray(obj) || isArrayLike(obj)) {
  13. var isPrimitive = typeof obj !== 'object';
  14. for (key = 0, length = obj.length; key < length; key++) {
  15. if (isPrimitive || key in obj) {
  16. iterator.call(context, obj[key], key, obj);
  17. }
  18. }
  19. } else if (obj.forEach && obj.forEach !== forEach) {
  20. obj.forEach(iterator, context, obj);
  21. } else if (isBlankObject(obj)) {
  22. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  23. for (key in obj) {
  24. iterator.call(context, obj[key], key, obj);
  25. }
  26. } else if (typeof obj.hasOwnProperty === 'function') {
  27. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  28. for (key in obj) {
  29. if (obj.hasOwnProperty(key)) {
  30. iterator.call(context, obj[key], key, obj);
  31. }
  32. }
  33. } else {
  34. // Slow path for objects which do not have a method `hasOwnProperty`
  35. for (key in obj) {
  36. if (hasOwnProperty.call(obj, key)) {
  37. iterator.call(context, obj[key], key, obj);
  38. }
  39. }
  40. }
  41. }
  42. return obj;
  43. }

官方描述:

forEach方法可以遍历数组或对象,函数有三个参数为别为:value,key,obj。
1)、value value指当遍历的对象或数组元素当前的值
2)、 key 是对象属性的的key或者数组的索引
3)、 obj obj即被遍历的对象或数组本身

示例:

  1. var values = {name: 'misko', gender: 'male'};
  2. var log = [];
  3. angular.forEach(values, function(value, key) {
  4. this.push(key + ': ' + value);
  5. }, log);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行