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 ?
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 ?
-
1
The issue is
obj.x
(x
is an identifier used as a property name) vs.obj[x]
(x
is an expression which is evaluated and then used as the property name) which has been covered already elsewhere. It has nothing to do with thefor...in
. – user166390 Commented Apr 19, 2012 at 18:11
5 Answers
Reset to default 8When you write obj.x
, this literally looks for a property named "x" in obj
— just like obj.size
would look for a property named "size". x
is not defined for your objects, so it es out as nothing. The correct way of writing it — obj[x]
— uses the variable x
to 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:
obj.x
obj["x"]
So when you write x
after obj.
, it converts that x
into a string — it's not a variable anymore.
The bracket syntax is used to receive a property whose name is the expression (expression can be a literal, a variable or something more plex):
var x = "a";
{a:0, b:1}[x] == 0;
The dot syntax is used to receive the property with exactly that name:
({a:0, x:1}).x == 1;
In your for-in-loop, the variable x
holds the property name. You are trying to acess the property named "x"
, which is not defined.
Use the bracket form (obj[x]
) when the property name is stored in a variable named "x" and the attribute form (obj.x
) when the property name is literally "x".
For example:
var o = {foo:1};
o.foo; // => 1
var x = 'foo';
o[x]; // => 1, since x='foo' and has a property named "foo".
o.x; // => undefined, since "o" has no property named "x".
Try
for(var x in obj){
console.log(obj[x]);
}
This works for me:
var obj = {uname:"OdO", age:"22"};
for (x in obj) {
document.write(obj[x.toString()] + "<br>");
}
http://jsfiddle/zA8HB/