如何遍历对象并获取quiz对象首个条目的question属性?
遍历对象并获取第一个条目question属性的解决方案
嘿,这事儿不难,我给你拆解成两个部分来实现:
1. 获取第一个条目的"question"属性
你可以直接通过键名访问,因为第一个条目的键是"0":
const quiz = { "0": { question: "Who was the lead-developer behind 'Grand Theft Auto V'?", answers: [ "Rockstar Games", "Rockstar North", "2K Games", "Activision" ], correct: 2, clip: "https://giphy.com/embed/l41lXyGaSM2Gko4WA" }, "1": { question: "'The Elder Scrolls V: Skyrim' is part of which genre?", answers: [ "massively multiplayer online role-playing game (MMORPG)", "platformer", "real-time strategy game (RTS)", "action role-playing game (ARPG)" ] } }; // 直接通过键名获取 const firstQuestion = quiz["0"].question; console.log(firstQuestion); // 输出: Who was the lead-developer behind 'Grand Theft Auto V'?
如果担心未来键名可能变化(比如不是从"0"开始),用Object.values()更通用,它会返回对象所有值的数组,取第一个元素就行:
const firstQuestion = Object.values(quiz)[0].question; console.log(firstQuestion);
2. 遍历整个quiz对象
有几种常用的遍历方式,按需选择:
方式一:for...in循环(遍历键名)
for (const key in quiz) { if (quiz.hasOwnProperty(key)) { // 确保只遍历对象自身的属性,避免原型链上的属性 const item = quiz[key]; console.log(`第${key}题: ${item.question}`); // 还可以访问answers、correct等其他属性 } }
方式二:Object.keys() + 数组forEach(遍历键名)
Object.keys(quiz).forEach(key => { const item = quiz[key]; console.log(`题目${key}: ${item.question}`); });
方式三:Object.values() + 数组forEach(直接遍历值)
如果不需要键名,直接遍历每个条目对象:
Object.values(quiz).forEach(item => { console.log(`问题: ${item.question}`); console.log(`选项: ${item.answers.join(', ')}`); });
方式四:Object.entries() + 数组forEach(同时获取键和值)
Object.entries(quiz).forEach(([key, item]) => { console.log(`序号${key}: ${item.question}`); });
这些方法都能帮你完整遍历整个quiz对象,根据你的实际需求选最顺手的就行~
内容的提问来源于stack exchange,提问作者Teodor Tița
相关产品推荐
相关产品推荐

