我不知道如何填充数组并在定位路线后立即显示它,我从nodeJs开始。
目前我能够控制台记录对象列表,我想填充一个数组并在执行 localhost:3000/时显示它
sortGroup=(group)=> {
for (const entry of group.entries) {
console.log(`Entry: ${field(entry, 'Name')}: UserName: ${field(entry, 'Surname')} || Age: ${field(entry, 'Age')} || Age: ${field(entry,'Address')}`)
}
for (const subGroup of group.groups) {
sortGroup(subGroup)
}
}
app.get('/',async (req, res) => {
res.send(`<h1> I want to display the table</h1>`)
})
最佳答案
您可以使用push
方法向数组添加新元素
sortGroup = (group, result = [])=> {
for (const entry of group.entries) {
// Notice that I'm using push method
result.push(`Entry: ${field(entry, 'Name')}: UserName: ${field(entry, 'Surname')} || Password: ${field(entry, 'Age')} || URL: ${field(entry,'Address')}`)
}
for (const subGroup of group.groups) {
sortGroup(subGroup, result)
}
return result
}
app.get('/',async (req, res) => {
// call sortGroup method
const group = []; // You need to populate group somehow here
const result = [];
// As you are calling the below function recursively, its good to pass the array
sortGroup(group, result)
return res.json(
// you can add any object here
result
);
})
关于javascript - 使用 for 循环填充数组并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54170620/