javascript - Why I get different results? use name.property and name[property] -
/*enumeration
the in statement can loop on of property names in object. enumeration include functions , prototype properties. */
//the first code write
var fruit = { apple: 2, orange: 5, pear:1 }, sentence = 'i have', quantity; (kind in fruit) { quantity = fruit[kind]; sentence += quantity + '' + kind + (quantity === 1?'': 's') + ', '; } sentence = sentence.substr(0,sentence.length-2) + '.'; alert(sentence);
//the second code write
var fruit = { apple: 2, orange: 5, pear:1 }, sentence = 'i have', quantity;// (kind in fruit) { quantity = fruit.kind; sentence += quantity + '' + kind + (quantity === 1?'': 's') + ', '; } sentence = sentence.substr(0,sentence.length-2) + '.'; alert(sentence);
the root of problem difference between accessing properties in dot (obj.prop) vs array notation (obj[prop]).
- obj.prop means access property named "prop" that's accessible obj object.
- obj[prop] on other hand means: determine string value of prop variable , access property matching string value on obj object.
in first case:
for (kind in fruit) { quantity = fruit[kind]; }
the kind variable gets assigned strings "apple", "orange", "pear" during loop execution. you're doing access fruit["apple"] (which equivalent fruit.apple), fruit["orange"] (or fruit.orange), , fruit["pear"] or (fruit.pear).
in second case:
for (kind in fruit) { quantity = fruit.kind; ... }
you're accessing kind property of fruit object. since fruit object doesn't have kind property, you'll undefined.
if want learn more how property access resolved in javascript, can take @ secrets of javascript ninja book - has helped me.
Comments
Post a Comment