The following code :
var obj = {uname:"OdO", age:"22"};
alert(obj.uname);
results in:
OdO
Now, using the same concept in a for..in statement :
for (x in obj) {
document.write(obj.x+"<br>");
}
I expected it to print the following:
OdO
22
but it prints :
undefined
undefined
And to achieve printing looping in the elements, it should be written as an array elements like this:
for (x in obj) {
document.write(obj[x]+"<br>");
}
Then, why the first syntax doesn’t work, however it works out of the for..in statement ?
When you write
obj.x, this literally looks for a property named “x” inobj— just likeobj.sizewould look for a property named “size”.xis not defined for your objects, so it comes out as nothing. The correct way of writing it —obj[x]— uses the variablexto look up a property in the object. The bracket syntax uses the value inside the brackets to look up the property, while the dot syntax turns the property name into a string. So these two are equivalent:So when you write
xafterobj., it converts thatxinto a string — it’s not a variable anymore.