所以我有两个for循环。在第一个循环中,消息正好说出了我想说的内容; Hello Herbert, Hello Peter
。
但在第二个中它说; Hello undefined
。
这两个代码块之间有什么区别,为什么第二个代码块返回undefined
?
let people = [
{
name: "Herbert",
occupation: "Vildstaed",
language: ["Finnish", "English", "German"]
},
{
name: "Peter",
occupation: "Skalnstead",
language: ["German", "Livonian Dialect"]
}
];
for(var i = 0; i < people.length; i++){
alert("Hello " + people[i].name)
}
for(let person in people) {
alert("Hello " + person.name)
}
&#13;
答案 0 :(得分:2)
let people = [
{
name: "Herbert",
occupation: "Vildstaed",
language: ["Finnish", "English", "German"]
},
{
name: "Peter",
occupation: "Skalnstead",
language: ["German", "Livonian Dialect"]
}
];
for(var i = 0; i < people.length; i++){
alert("Hello " + people[i].name)
}
for(let person in people) {
console.log(person);
alert("Hello " + people[person].name)
}
&#13;
正如您所看到的,人们获得的值是数组的索引,因此您需要使用人员[person]
来访问它答案 1 :(得分:1)
For in
循环将返回keys
,而不是对象。因此,对于第二种情况,person
不是您期望的那种情况。您只需显示person
即可看到它。
let people = [
{
name: "Herbert",
occupation: "Vildstaed",
language: ["Finnish", "English", "German"]
},
{
name: "Peter",
occupation: "Skalnstead",
language: ["German", "Livonian Dialect"]
}
];
for(let person in people) {
alert("Hello " + person)
}
&#13;
要执行您想要的操作,您可以在for of
版本中使用ES6
循环,或者只需按键获取
let people = [
{
name: "Herbert",
occupation: "Vildstaed",
language: ["Finnish", "English", "German"]
},
{
name: "Peter",
occupation: "Skalnstead",
language: ["German", "Livonian Dialect"]
}
];
for(let person of people) {
alert("Hello " + person.name)
}
for(let person in people) {
alert("Hello " + people[person].name)
}
&#13;
答案 2 :(得分:0)
for(let person of people) {
alert("Hello " + person.name)
}