【问题标题】:difference between javascript foreach loop, for..in and angular forEach loop.?javascript foreach 循环、for..in 和角度 forEach 循环之间的区别。?
【发布时间】:2017-01-05 20:42:28
【问题描述】:

我是 Angular 框架的新手。当我想以角度迭代 json 对象时,我使用了 javascript foreachfor..in 循环。

后来我才知道 Angular 本身有一个 angular.forEach 循环来迭代对象。

如何比较 angular.forEach 与 javascript for..inforeach 循环的性能?

为什么我们应该使用angular.forEach 而不是javascript foreachfor..in??

请给我一些例子和使用它的理由,它显示了性能。

谢谢:)

【问题讨论】:

    标签: javascript angularjs loops foreach


    【解决方案1】:

    Angular forEach - 为 obj 集合中的每个项目调用一次迭代器函数,它可以是对象或数组。

    var values = {name: 'misko', gender: 'male'};
    angular.forEach(values, function(value, key) {
      console.log(key + ': ' + value);
    });
    
    // Output:
    // "name: misko"
    // "gender: male"
    

    for..in - 以任意顺序迭代对象的enumerable properties。对于每个不同的属性,可以执行语句。

    var obj = {a:1, b:2, c:3};
    
    for (var prop in obj) {
      console.log("obj." + prop + " = " + obj[prop]);
    }
    
    // Output:
    // "obj.a = 1"
    // "obj.b = 2"
    // "obj.c = 3"
    

    forEach - 方法对每个数组元素执行一次提供的函数。

    // Notice that index 2 is skipped since there is no item at
    // that position in the array.
    [2, 5, , 9].forEach(function (element, index, array) {
      console.log('a[' + index + '] = ' + element);
    });
    // logs:
    // a[0] = 2
    // a[1] = 5
    // a[3] = 9
    

    就性能而言,这取决于您正在使用的数据结构,如果是Array,我建议使用Angular.forEach or native forEach,如果是Objectfor..in 将是最好的,但是看起来Angular.forEach 也能很好地处理对象。取决于您使用的数据量。如果它很大,我建议你使用像 Lodash or Underscore 这样的库,它们可以很好地处理数据。

    【讨论】:

      【解决方案2】:

      angular.forEach 基本上是一个 polyfill。

      因此,如果您使用的是 angular,则浏览器是否较旧无关紧要,因为 angular 会在需要时提供替代品。

      在代码中它看起来像这样:

      if (!Array.prototype.forEach) {
          Array.prototype.forEach = function(...) {
              // angulars own implementation
          }
      }
      

      还有一些其他的区别,例如

      • angular.forEach 支持对对象的迭代;
      • angular.forEach 将对象/数组作为它的第一个参数。

      【讨论】:

      • 没错,数据结构的类型也很重要
      • 错了,if (!Array.forEach) { > if (!Array.prototype.forEach) {。在这种情况下,!Array.forEach 将始终为 trueforEachprototype 属性中可用。
      • angular.forEach 性能优于普通的for/foreach?
      猜你喜欢
      • 1970-01-01
      • 2015-11-18
      • 2019-10-01
      • 1970-01-01
      • 2018-01-14
      • 2016-07-08
      • 2015-02-25
      • 1970-01-01
      • 2018-11-14
      相关资源
      最近更新 更多