You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将表单提交的姓名打印为有序列表项?问题求助

问题描述

我正在开发一个提交功能,用户可输入多个姓名,提交后每个姓名需按升序显示为有序列表项,示例如下:

    1. Bruce Wayne

    2. Peter Parker

    3. Clark Kent

我尝试通过空数组存储表单提交的姓名,再将其渲染为列表项,但未成功实现需求。以下是我的代码:

JS部分

app.post("/submit", (req, res) => {
    const clientName = req.body["fName"] + req.body["mName"] + req.body["lName"];
    const nameList = [];
    const characterName = nameList.push(clientName)

    res.render("index.ejs", nameList, { 
        userName: clientName,
    });
});

EJS部分

<% if (locals.userName) { %>

    <ul>
        <% for (let userName = 0; userName < locals.characterName; userName++) { %>

            <li>
                <%= nameList[userName] %>
            </li>
        <% } %>
    </ul>

<% } else { %>

    <p>No Names to Display</p>

<% } %>

请帮忙排查问题并实现需求。


问题排查与解决方案

核心问题点

  1. 数组存储逻辑错误:每次请求都会新建空数组nameList,无法累积存储多次提交的姓名;且push方法返回的是数组新长度,不是数组本身,characterName存储的是长度而非数组。
  2. 模板渲染参数错误:res.render的第二个参数必须是渲染数据对象,直接传数组会导致模板无法正确获取变量。
  3. 模板变量引用错误:EJS中无法直接访问未传入的nameList;循环变量命名与传入的userName冲突;需求是有序列表,却使用了<ul>无序列表。
  4. 缺少排序逻辑:没有对姓名数组做升序排序处理。

修正后的代码

1. JS部分(注:全局数组仅做演示,生产环境需用数据库/文件做持久化存储)

// 全局数组存储提交的姓名(生产环境请替换为数据库存储)
const nameList = [];

app.post("/submit", (req, res) => {
    // 拼接姓名,处理中间名为空的情况
    const firstName = req.body.fName || '';
    const middleName = req.body.mName ? ` ${req.body.mName}` : '';
    const lastName = req.body.lName || '';
    const fullName = `${firstName}${middleName} ${lastName}`.trim();

    if (fullName) {
        nameList.push(fullName);
        // 按姓名升序排序
        nameList.sort((a, b) => a.localeCompare(b));
    }

    // 将姓名数组传入模板
    res.render("index.ejs", { 
        nameList: nameList
    });
});

2. EJS部分

<% if (nameList && nameList.length > 0) { %>
    <!-- 使用有序列表<ol>匹配需求 -->
    <ol>
        <% nameList.forEach(name => { %>
            <li><%= name %></li>
        <% }) %>
    </ol>
<% } else { %>
    <p>No Names to Display</p>
<% } %>

额外说明

  • 若要支持多用户提交且数据不丢失,必须替换全局数组为数据库(如MongoDB、MySQL)或文件存储。
  • 姓名拼接时处理了中间名为空的场景,避免出现多余空格。
  • 使用localeCompare方法排序,更符合人名的自然排序规则(支持多语言)。

内容的提问来源于stack exchange,提问作者Abdul-Jalil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:07:40