我尝试循环嵌套在对象内部的前端开发人员的名称(请参阅代码),当我将其打印到控制台时,它说显示未定义。
var employees =
{
sales: {
manager: {
name: 'Evan',
gender: 'Male',
age: 41,
salary: 2000
},
sales_rep: {
name: 'Cilian',
gender: 'Male',
age: 24,
slary: 1000
},
sales_executive: {
name: 'Joanna',
gender: 'Female',
age: 23,
salary: 1000
}
},
engineering: {
manager: {
name: 'Mike',
gender: 'Male',
age: 39,
salary: 3000
},
designer: {
userExperience: {
name: 'Amy',
gender: 'Female',
age: 25,
salary: 1000
},
userInterface: {
name: 'Jenna',
gender: 'Female',
age: 24,
salary: 1000
}
},
developer: {
frontEndDeveloper: {
name: 'John',
gender: 'Male',
age: 27,
salary: 2000
},
backEndDeveloper: {
name: 'Felix',
gender: 'Male',
age: 28,
salary: 2000
}
}
}
}
;
var display;
for (let sector in employees) {
display = `${sector}: ${employees.engineering.developer[sector].name}`;
}
首先,我认为显示范围在 for 循环内,因此我将显示变量移到了 for 循环之外。自从我开始学习 JavaScript 已经过去了 4 天,所以我对这些概念还很陌生。
您的代码中有一个小错误。 您可以直接从对象中获取 frontEndDeveloper 名称。请检查下面更新的代码。
var employees =
{
sales: {
manager: {
name: 'Evan',
gender: 'Male',
age: 41,
salary: 2000
},
sales_rep: {
name: 'Cilian',
gender: 'Male',
age: 24,
slary: 1000
},
sales_executive: {
name: 'Joanna',
gender: 'Female',
age: 23,
salary: 1000
}
},
engineering: {
manager: {
name: 'Mike',
gender: 'Male',
age: 39,
salary: 3000
},
designer: {
userExperience: {
name: 'Amy',
gender: 'Female',
age: 25,
salary: 1000
},
userInterface: {
name: 'Jenna',
gender: 'Female',
age: 24,
salary: 1000
}
},
developer: {
frontEndDeveloper: {
name: 'John',
gender: 'Male',
age: 27,
salary: 2000
},
backEndDeveloper: {
name: 'Felix',
gender: 'Male',
age: 28,
salary: 2000
}
}
}
}
;
var display = employees.engineering.developer.frontEndDeveloper.name;
console.log(display);
让我知道它是否适合您。