我是 JavaScript 新手,现在正在学习 for...in 循环和对象。我正在用下面的例子练习:
let spaceship = {
crew: {
captain: {
name: 'Lily',
degree: 'Computer Engineering',
cheerTeam() { console.log('You got this!') }
},
'chief officer': {
name: 'Dan',
degree: 'Aerospace Engineering',
agree() { console.log('I agree, captain!') }
},
medic: {
name: 'Clementine',
degree: 'Physics',
announce() { console.log(`Jets on!`) } },
translator: {
name: 'Shauna',
degree: 'Conservation Science',
powerFuel() { console.log('The tank is full!') }
}
}
};
for (let crewMember in spaceship.crew){
console.log(`${crewMember}: ${crewMember.name}`);
}
此代码的输出是控制台成功记录了crewMember,但没有记录crewMember.name。如图所示,crewMember.name 未定义。 另一方面,当我将日志语句更改为:
for (let crewMember in spaceship.crew){
console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);
}
机组人员姓名已成功登录。我不明白为什么我能够在console.log语句的前半部分不通过spaceship.crew来访问船员,但在后半部分我必须通过spaceship.crew。
正如评论中所说。
for in
循环获取属性名称作为 key
。所以它是 captain
或 'chief officer'
的占位符。您可以通过点符号和括号符号访问属性。使用变量时使用括号:
所以:
spaceship.crew[crewMember]
这应该可行。参见示例:
let spaceship = {
crew: {
captain: {
name: 'Lily',
degree: 'Computer Engineering',
cheerTeam() { console.log('You got this!') }
},
'chief officer': {
name: 'Dan',
degree: 'Aerospace Engineering',
agree() { console.log('I agree, captain!') }
},
medic: {
name: 'Clementine',
degree: 'Physics',
announce() { console.log(`Jets on!`) } },
translator: {
name: 'Shauna',
degree: 'Conservation Science',
powerFuel() { console.log('The tank is full!') }
}
}
};
for (let crewMember in spaceship.crew){
console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);
}