www.webdeveloper.com
Results 1 to 3 of 3

Thread: help: object.property==object["property"] ? true

  1. #1
    Join Date
    Jul 2012
    Posts
    5

    Question help: object.property==object["property"] ? true

    var a={};
    var i=0;
    while(i<10){
    a[i]=i*i;
    i++;
    }
    //work!
    if (a.["5"]==25)
    alert("success");
    //error!
    if (a.5==25)
    alert("success");
    why error?

  2. #2
    Join Date
    Mar 2009
    Posts
    497
    An object property can only be accessed by the "dot" notation if its name conforms to the rules concerning valid names for javascript variables. In your case, a variable that begins with '5' is illegal as a js variable name.

    However, with the square bracket notation the property name doesn't have to conform to the naming conventions. That's what is happening. An object can be given some property names that cannot be accessed by the "dot" method.

  3. #3
    Join Date
    Jul 2012
    Posts
    5
    Quote Originally Posted by Tcobb View Post
    An object property can only be accessed by the "dot" notation if its name conforms to the rules concerning valid names for javascript variables. In your case, a variable that begins with '5' is illegal as a js variable name.

    However, with the square bracket notation the property name doesn't have to conform to the naming conventions. That's what is happening. An object can be given some property names that cannot be accessed by the "dot" method.
    thanks Tcobb...but I don't know why this is illegal.
    I am reading <javascript: the definite guide>section7.3

    Section 7.3. Objects as Associative Arrays
    You've seen the . operator used to access the properties of an object. It is also
    possible to use the [] operator, which is more commonly used with arrays, to
    access these properties. Thus, the following two JavaScript expressions have the
    same value:

    object.property
    object["property"]

    The important difference to note between these two syntaxes is that in the first,
    the property name is an identifier, and in the second, the property name is a
    string. You'll see why this is so important shortly.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles