迭代对象数组javascript - 奇怪的行为? [英] Iterating over array of objects javascript - odd behaviour?
本文介绍了迭代对象数组javascript - 奇怪的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var myArr = [{a:1, b:2}, {c:3, d:4}];
for (var item in myArr) {
console.log(item);
}
项目返回键(例如:0,1)而不是对象本身。为什么?
Item returns the key (ex: 0, 1) instead of the object itself. Why?
推荐答案
Douglas Crockford推荐 JavaScript:好的部分,以避免在语句中使用。
Douglas Crockford recommends in JavaScript: The Good Parts to avoid using the for in
statement.
如果在中使用来循环对象中的属性名称,则 结果不会被排序 。
If you use for in
to loop over property names in an object, the results are not ordered.
循环中的最适合迭代名称值对,以及<$每个
循环的c $ c>最适合迭代值,即数组。
The for in
loop is best for iterating over name-value pairs, and the for each
loop best for iterating over values i.e arrays.
例如,
var o = {'name':'Batman', 'age':33, 'city':'Gotham City'};
for (var p in o) {
console.log(p+': '+o[p]);
}
如果我们使用For,我们无法获得属性名称上述对象的每个循环。
There’s no way we can get the property name if we were to use the For Each Loop for the above object.
注意:
- For in 循环最适合名称 - 值对。
- For Each 循环最适合可迭代值。例如:数组和对象,如果您对该属性的名称不感兴趣。
- The For in Loop is best for name-value pairs.
- The For Each Loop is best for iterable values. Eg: arrays, and objects if you are not interested in the name of the property.
这篇关于迭代对象数组javascript - 奇怪的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文