【问题标题】:Populate an array with a for loop and display it使用 for 循环填充数组并显示它
【发布时间】:2019-01-14 00:28:30
【问题描述】:

我不知道如何填充数组并在我定位路由后立即显示它,我从 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>`)
})

【问题讨论】:

    标签: javascript arrays node.js express


    【解决方案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
        );
    })
    

    【讨论】:

    • 谢谢你的回答有没有办法在app.get中显示?
    • 这取决于你如何调用 sortGroup 方法。
    • 我已经修改了我的答案以满足您的需求。
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    相关资源
    最近更新 更多