Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  125] [ 6]  / answers: 1 / hits: 61569  / 13 Years ago, sun, july 3, 2011, 12:00:00
var myArr = [{a:1, b:2}, {c:3, d:4}];

for (var item in myArr) {
console.log(item);
}


Item returns the key (ex: 0, 1) instead of the object itself. Why?


More From » javascript

 Answers
29

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.



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.



E.g,



var o = {'name':'Batman', 'age':33, 'city':'Gotham City'};
for (var p in o) {
console.log(p+': '+o[p]);
}


There’s no way we can get the property name if we were to use the For Each Loop for the above object.






Note :




  1. The For in Loop is best for name-value pairs.

  2. The For Each Loop is best for iterable values. Eg: arrays, and objects if you are not interested in the name of the property.


[#91375] Friday, July 1, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;