Iterating over array of objects javascript - odd behaviour? -


var myarr = [{a:1, b:2}, {c:3, d:4}];  (var item in myarr) {     console.log(item); } 

item returns key (ex: 0, 1) instead of object itself. why?

douglas crockford recommends in javascript: parts avoid using for in statement.

if use for in loop on property names in object, results not ordered.

the for in loop best iterating on name-value pairs, , for each loop best iterating on values i.e arrays.

e.g,

var o = {'name':'batman', 'age':33, 'city':'gotham city'};    (var p in o) {         console.log(p+': '+o[p]);     } 

there’s no way can property name if use each loop above object.


note :

  1. the for in loop best name-value pairs.
  2. the for each loop best iterable values. eg: arrays, , objects if not interested in name of property.

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -