Ise*_*mar 22 javascript foreach loops angularjs
我是角度框架的新手.当我想以角度迭代json对象时,我使用了javascript foreach
和for..in
循环.
后来我才知道angular本身有一个angular.forEach
迭代对象的循环.
我怎样才能比较angular.forEach
javascript for..in
和foreach
循环的性能?
为什么我们应该使用angular.forEach
而不是javascript foreach
和for..in
??
请给我一些使用它的例子和理由,它显示了性能.
谢谢 :)
aki*_*ide 21
Angular forEach - 为obj集合中的每个项目调用迭代器函数一次,可以是对象或数组.
var values = {name: 'misko', gender: 'male'};
angular.forEach(values, function(value, key) {
console.log(key + ': ' + value);
});
// Output:
// "name: misko"
// "gender: male"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
在性能方面,它取决于您正在使用的数据结构,如果它是Array
我建议使用的Angular.forEach or native forEach
,如果它Object
for..in
是最好的,但它似乎Angular.forEach
也很好地处理对象.取决于您使用的数据量.如果它是巨大的,我会建议你使用库Lodash or Underscore
,他们很好地处理数据操作.
angular.forEach
基本上是一个polyfill.
因此,如果您使用角度,则浏览器是否较旧并不重要,因为如果需要,角度将提供替换.
在代码中它看起来像这样:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(...) {
// angulars own implementation
}
}
Run Code Online (Sandbox Code Playgroud)
还有一些其他的差异,例如