0

A similar question is asked, but it didn't meet the conditions I've met.

I know that to access a property I can use either point notation or bracket notation. An article at jibbering.com states the same, also this answer. The Specifiacation says the same.

I have this example ( fiddle ) and there is a difference:

var utils = {
    myString: "boo",
    myNumber: 99,
    justNULL: null
};

for (var i in utils) {
    document.write ( i + " = " + utils.i + "<br/>" ); //result - undefined
    document.write ( i + " = " + utils[i] + "<br/>" );//result - the actual value
}​

What I am missing here? Is it something about the usage of the for..in or the definition of the object?

Community
  • 1
  • 1
Bakudan
  • 19,134
  • 9
  • 53
  • 73
  • The member access operator (the dot) _is_ slightly different... Anything that follows it must be a valid JavaScript identifier. So, for example, `obj.foo = 'bar';` works, but `obj.123 = 'bar';` does not, because identifiers can't start with a number. However, `obj['123'] = 'bar';` works. – voithos Apr 16 '12 at 06:51

2 Answers2

1

You need to use utils[i] format here because i is a string and a string reference can not be used to access a property using the use object.property format.

var obj = {};
obj.foo = 'test';

obj.'foo' // doesn't work
obj['foo'] // works
GillesC
  • 10,647
  • 3
  • 40
  • 55
1

No, it's the usage of the point notation that is the problem.

You can't use a variable for the property name when you are using the point notation. The expression utils.i will access the property i in the object, it won't use the variable i for the name.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005