JavaScript我可以直接访问对象中属性内的属性吗?
在这个对象中,我想以[用户名,技能]的形式打印出一个数组。我知道这些对象没有索引。是否可以检测技能
属性并仅打印出其值?
const users = {
Alex: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
}
}
我首先尝试了下面的代码,但是有一个错误,它无法读取未定义的属性(读取0)。
let userId = Object.keys(users); //(3) ['Alex', 'Asab', 'Brook']
for (let i = 0; i < userId.length; i++) {
let userSkills = users.userId[i].skills;
console.log(userId, userSkills);
}
这是我唯一的途径检查所有技能吗?
console.log(users.Alex.skills);
console.log(users.Asab.skills);
console.log(users.Brooks.skills);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如评论中所述,您应该使用括号符号。
链接:
另外,您可以使用它缩短代码:
关于数组方法,您可以在此处阅读:
https:/https:/ /javascript.info/array-methods
As said in comments, you should use bracket notation.
Links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
https://javascript.info/object
Also, you can use this to shorten your code:
About array methods you can read here:
https://javascript.info/array-methods
尝试一下,它将对您有用
Try this, It will work for you
您可以使用
object.entries
并为其映射You can use
Object.entries
and map for it您快到了 -
使用括号符号而不是点符号。
因为所有时间点表示法是不可接受的。 - 。
像
阅读更多:
You're almost there -
Use Bracket Notation instead of Dot Notation.
Because all the time dot notation is not acceptable. Like - .number, .dependingValue, .anyCalculation, numericValue.something
Javascript mixes up decimal.
Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors