JavaScript中forEach循环、for..in循环和Angular的forEach循环有何不同?

22
我刚接触Angular框架。当我想在Angular中迭代JSON对象时,我使用了JavaScript的forEachfor..in循环。
后来我知道Angular本身有一个angular.forEach循环来迭代对象。
如何比较angular.forEach与JavaScript的for..inforEach循环的性能?
为什么我们应该使用angular.forEach而不是JavaScript的forEachfor..in
请给我一些使用它的例子和理由,以展示其性能。
谢谢 :)
2个回答

23

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

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

// Output:
// "name: misko"
// "gender: male"

for..in - 遍历对象的可枚举属性,顺序任意。对于每个不同的属性,可以执行语句。

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或本地forEach;如果是Objectfor...in将是最好的选择,不过Angular.forEach似乎也很擅长处理对象。根据你要处理的数据量大小,如果非常庞大,我建议你使用像Lodash或Underscore这样的库来处理数据操作。


10

angular.forEach基本上是一个 polyfill。

因此,如果你正在使用 angular,即使浏览器比较老,也没有关系,因为 angular 会在必要时提供替代方案。

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

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

除此之外,还有一些其他的区别:

  • angular.forEach支持对对象进行迭代;
  • angular.forEach以对象/数组作为其第一个参数。

真的,数据结构的类型也很重要。 - Akinjide
2
这里有一个错误, if (!Array.forEach) { 应该改成 if (!Array.prototype.forEach) {。在这种情况下,!Array.forEach 总是为 true。而且,forEach方法应该被调用在 prototype 属性中。 - user5066707
angular.forEach的性能比普通的for/foreach更好吗? - Vikas Bansal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接