简体   繁体   English

为什么在循环对象时不能显示属性的属性?

[英]Why can't I the properties of properties when looping an object?

Let's say I have this object: 假设我有这个对象:

const people = {
     frodo: { name: 'Frodo', age: 33 },
     aragorn: { name: 'Aragorn', age: 87 },
     legolas: { name: 'Legolas', age: 2931 }
}

And let's say I want to loop over the properties of that object, like this: 假设我要遍历该对象的属性,如下所示:

for (var person in people) {
    console.log(person.name);
}

I get undefined for any property of the person I tried to access. 对于尝试访问的人的任何财产,我都不确定。 Why does this happen, and what's the correct way to loop the properties of that object and still be able to access their own properties? 为什么会发生这种情况?循环该对象的属性并仍然能够访问其自己的属性的正确方法是什么?

The for ... in loop iterates over the keys (properties) of an object. for ... in循环遍历对象的键(属性)。 So 所以

for (var person in people) {
  console.log(people[person].name);
}

will get you the desired result. 将为您带来理想的结果。

The variable person will receive the values "frodo", "aragorn" and "legolas" during the execution of the loop which are the keys (properties) of your person object. 在循环执行期间,变量person将接收值“ frodo”,“ aragorn”和“ legolas”,它们是您的person对象的键(属性)。

You take the keys of the object with for ... in statement . 您可以使用for ... in语句获取对象的键。 Then you need it as property accessor fopr the object. 然后,您需要它作为对象的属性访问器。

 const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for (var person in people) { console.log(people[person].name); } 

You need to look at what person is within your code: 你需要看什么person是你的代码中:

 const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for(person in people) console.log(person); 

It's the name of the object, not the object itself. 它是对象的名称,而不是对象本身。 To access it you need to specify where the object is located: 要访问它,您需要指定对象的位置:

  const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for(person in people) { console.log( people[person].age, people[person].name, people[person] ); } 

for .. in returns every key in the object. for .. in返回对象中的每个键。 You can get the person by using the key. 您可以使用密钥来获得此人。

const people = {
     frodo: { name: 'Frodo', age: 33 },
     aragorn: { name: 'Aragorn', age: 87 },
     legolas: { name: 'Legolas', age: 2931 }
}

for(var key in people) {
    var person = people[key]
    console.log(person.name)
}

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

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