Javascript未定义的值而不是值

时间:2017-08-20 09:40:04

标签: javascript undefined

所以我有两个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;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
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;
&#13;
&#13;

正如您所看到的,人们获得的值是数组的索引,因此您需要使用人员[person]

来访问它

答案 1 :(得分:1)

For in循环将返回keys,而不是对象。因此,对于第二种情况,person不是您期望的那种情况。您只需显示person即可看到它。

&#13;
&#13;
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;
&#13;
&#13;

要执行您想要的操作,您可以在for of版本中使用ES6循环,或者只需按键获取

&#13;
&#13;
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;
&#13;
&#13;

答案 2 :(得分:0)

for(let person of people) {
   alert("Hello " + person.name)
}