javascript - 使用 for 循环填充数组并显示它

标签 javascript arrays node.js express

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

相关文章:

javascript - getElementById/InnerHTML 函数不起作用

javascript - 使用 webpack 从 scss 文件中提取 css

python - 如何在由 1D NumPy 数组(Python)中的值表示的索引处获取值为 1 的 2D NumPy 数组

java - Oracle VARRAY 如何用 Java 术语表示数据?

javascript - Node JS POST 请求返回未定义的正文

javascript - 获取 Firefox 扩展中的字体列表

javascript - 是否有一个 jQuery 或普通 javascript 插件主要使用 XHR 上传进度反馈并使用 flash 作为替代?

c - 在 C 中进行类型转换后复制数组的更快方法?

jquery - 如何使用 mongoosastic + AJAX 进行即时搜索?

javascript - NodeJS 严格模式