简体   繁体   中英

JavaScript:strange behavior of Objects

var person={fname:"John",lname:"Doe",age:25};
person.fname; //it gives a output John

for (x in person)
  {
  alert(person[x]); //works fine
  person.x;    //incorrect why???
  }

Can someone please explain the exact logic behind this?

var person = {fname:"John", lname:"Doe", age:25};

for (var x in person) {
    alert(person[x]); 
}

In the loop x assumes three different values: fname , lname and age . By doing person[x] you're trying to access three different properties. It's like doing person['fname'] , person['lname'] and person['age'] . They are the same thing to person.fname , person.lname and person.age , which are defined properties of the person object. If you do person.x you're trying to access an undeclared property x which correctly returns undefined .

The usage of [] is also known as bracket notation , which is needed in the case of iterations and other things, like setting a dynamic property to an object given by user input(for example), but they have a large usage range.

This is because Javascript can't decide if you want to access the x property of object person (for example if person={x:100,y:65}), or the property that is the value of the string x.

  • person[x] will evaluate x to it's value
  • person.x will take the property x

person.fname will give you fname object of person object.

person.lname will give you lname object of person object.

person.age will give you age object of person object.

for (x in person)
      {
        alert(person[x]);    
      }

it'll iterate through the person object. While in person.x; 'x' is an unknown property to person object.

It is better you should go through some basic javascript concepts, here and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM