gpt4 book ai didi

javascript - 迭代对象的数组列表及其属性

转载 作者:行者123 更新时间:2023-11-28 14:31:05 26 4
gpt4 key购买 nike

循环一个对象及其所有属性,然后移动到另一个对象等等的最佳方法是什么......

目前,我的代码仅循环 lvlTitle。而我想循环遍历 lvlTitle,然后转到 statements1、statement2 和 statements3,然后转到下一个对象。

谢谢。

这是 JavaScript:

// Different Levels
var lvls = {
start: {
lvlTitle: 'Lets Start!',
},
lvl1: {
lvlTitle: 'Drinks/Soda/water',
statement1: 'lvl1 info...',
statement2: 'lvl1 more info...',
statement3: 'lvl1 more more info...'
},
lvl2: {
lvlTitle: 'Portion Control/Meals',
statement1: 'lvl2 info...',
statement2: 'lvl2 more info...',
statement3: 'lvl2 more more info...'
},
lvl3: {
lvlTitle: 'Salt',
statement1: 'lvl3 info...',
statement2: 'lvl3 more info...',
statement3: 'lvl3 more more info...'
}
}

// Array of all the levels
var allLvls = [];

// Populate users array
for (var key in lvls) {
allLvls.push(lvls[key]);
}

console.log(allLvls[0].lvlTitle);


let myIndex = 1;
let printText = document.querySelector('.text-container');

printText.innerHTML = allLvls[0].lvlTitle;


function nextLevel() {
printText.innerHTML = allLvls[myIndex].lvlTitle;
myIndex = (myIndex + 1) % (allLvls.length);
};


printText.addEventListener('click', nextLevel);

这是 Html:

<div class="full-page">
<div class="click-container">
<ul class="text-container">
<li class="text-content">
<div></div>
</li>
</ul>
</div>

这里还有一个 jsFiddle: Iterate through Array List of Objects

最佳答案

您可以创建递归函数。它将是一个对象并创建一个列表(或您想要使用的任何 html 结构)。在该函数中查看每个属性,它是一个对象,如果不处理它,则将该对象传递回函数。这适用于嵌套在任意深度的对象,并且是一个值得了解的好技术:

// Different Levels
var lvls = {start: {lvlTitle: 'Lets Start!',},lvl1: {lvlTitle: 'Drinks/Soda/water',statement1: 'lvl1 info...',statement2: 'lvl1 more info...',statement3: 'lvl1 more more info...'},lvl2: {lvlTitle: 'Portion Control/Meals',statement1: 'lvl2 info...',statement2: 'lvl2 more info...',statement3: 'lvl2 more more info...'},lvl3: {lvlTitle: 'Salt',statement1: 'lvl3 info...',statement2: 'lvl3 more info...',statement3: 'lvl3 more more info...'}}

function printProps(obj){
let html = "<ul>"
Object.keys(obj).forEach(key => {
html += '<li>' + key + '</li>'
let next = (typeof obj[key] == 'object' ? printProps(obj[key]) : obj[key])
html += '<li>' + next + '</li>'
})
html += "</ul>"
return html
}

let d = document.getElementById('list')
d.innerHTML = printProps(lvls)
<div id = "list"></div>

关于javascript - 迭代对象的数组列表及其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com