1

This code will alert all the properties names in the object a. 0,1,2 and hello.

Object.prototype.hello = {};

var a = [1,2,3];

for ( var number in a ) {
    alert( number)
}

My question is, I can access the property hello by this syntax:

a.hello

But why can't I access a.0 which should be equal to 1. Isn't the array decleration creating "real properties"?

I know that I can access the properties by a[0] and a["hello"]

Simon Edström
  • 6,461
  • 7
  • 32
  • 52

4 Answers4

7

It's a syntax limitation. In JavaScript, identifier must not start with number, so 0 is not a valid one. a.0 will then produce syntax error.

Xion
  • 22,400
  • 10
  • 55
  • 79
  • Ok, so in the for ... in, I don't get the identifers name. So what does I get? – Simon Edström Sep 17 '12 at 12:33
  • @SimonEdström `for ... in` enumerates property names, which are arbitrary strings and therefore may or may not be an identifier. – Neil Sep 17 '12 at 12:49
3

Because:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($);

Alex K.
  • 171,639
  • 30
  • 264
  • 288
2

Items in an array are accessed using the syntax myArray[index]. The dot notation only allows you to access properties whose names are valid identifiers, and the index of an item in an array, being a number, does not qualify. Therefore, you have to use the more lenient bracket notation.

skunkfrukt
  • 1,550
  • 1
  • 13
  • 22
  • 1
    Items in the array are objects in the protoype, you just can't access them with dot notation because they start with a number. – howderek Sep 17 '12 at 12:32
1

JavaScript identifiers cannot begin with a digit. The property that you are trying to access is an identifier inside the object.

You will find here https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals this fragment:

Variables

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, and _name.

gabitzish
  • 9,535
  • 7
  • 44
  • 65