我不知道如何填充数组并在我以路线为目标时立即显示它,而我是从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>`)
})
答案 0 :(得分:1)
您可以使用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
);
})