oop - Accessing object properties in javascript using for loop? -
consider following object:
var nyc = { fullname: "new york city", mayor: "bill de blasio", population: 8000000, boroughs: 5 };
when try access each of properties using loop:
for(var key in nyc){ console.log(nyc[key]); }
it returns correct output(property values), but...
for(var key in nyc){ console.log(nyc.key); }
this return "undefined" on 4 lines
why strange behavior, since both:
console.log(nyc.fullname); console.log(nyc['fullname']);
give same o/p.
nyc.key
looks property name key
, not property name in variable key
. first example, nyc[key]
, correct way use property name variable.
in javascript, can access object properties using dot notation , property name literal (obj.foo
), or brackets notation , property name string (obj["foo"]
). in second case, can use expression string, including variable lookup. (in es6, can use symbol
s brackets notation, it's not relevant here.)
Comments
Post a Comment