简体   繁体   English

JavaScript:对象的奇怪行为

[英]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 . 在循环中,x假定三个不同的值: fnamelnameage By doing person[x] you're trying to access three different properties. 通过执行person[x]您试图访问三个不同的属性。 It's like doing person['fname'] , person['lname'] and person['age'] . 这就像在做person['fname']person['lname']person['age'] They are the same thing to person.fname , person.lname and person.age , which are defined properties of the person object. 他们是同样的事情person.fnameperson.lnameperson.age ,其被定义的人对象的属性 If you do person.x you're trying to access an undeclared property x which correctly returns undefined . 如果执行person.x ,则尝试访问未声明的属性x ,该属性正确返回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. 这是因为Javascript无法决定您是否要访问对象person 的x属性(例如,如果person = {x:100,y:65}) 还是字符串 x 的值

  • person[x] will evaluate x to it's value person [x]将对x求值
  • person.x will take the property x person.x将拥有财产x

person.fname will give you fname object of person object. person.fname将为您提供person对象的fname对象。

person.lname will give you lname object of person object. person.lname将为您提供person对象的lname对象。

person.age will give you age object of person object. person.age会给你age的对象person对象。

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

it'll iterate through the person object. 它将遍历person对象。 While in person.x; person.x; 'x' is an unknown property to person object. “ x”是人员对象的未知属性。

It is better you should go through some basic javascript concepts, here and here . 最好在这里这里通读一些基本的javascript概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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