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

遍历JS对象生成Modal输入框时出现undefined问题排查

问题:Modal输入框下方出现额外的undefined文本

我正在学习JavaScript,尝试从指定JS对象的3个属性(softwarename、softwareprovider、softwareprovidercontactemail)生成输入框,功能基本正常,但Modal中三个输入框下方会额外显示一个undefined。相关代码如下:

目标JS对象

{
  "createdBy" : "System",
  "createdDate" : "2015-12-31T05:00:00.000+00:00",
  "lastModifiedBy" : "System",
  "lastModifiedDate" : "2023-12-31T05:00:00.000+00:00",
  "id" : 21,
  "softwarename" : "KeePass",
  "softwareprovider" : "KeePass",
  "softwareprovidercontactemail" : "admin@KeePass.com",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/softwares/21"
    },
    "appSoftware" : {
      "href" : "http://localhost:8080/softwares/21"
    }
  }
}
<div class="modal" tabindex="-1" id="myModal">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Modal title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="modalBody">
                <p>Modal body text goes here.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

原始JavaScript函数

function myEditObjIterFunction(formData) {
    let modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('myModal'));
    var target = document.querySelector("#modalBody");
    var htmlFromObj = '';
    Object.entries(formData).forEach(([key, value]) => {
        if (key == 'softwarename') {
            htmlFromObj += '<label>' + key + '</label></br><input  type="text" value="'+ value +'" id="' + key + '">' + '</br>';
        } else if (key == 'softwareprovider') {
            htmlFromObj += '<label>' + key + '</label></br><input  type="text" value="'+ value +'" id="' + key + '">' + '</br>';
        } else if (key == 'softwareprovidercontactemail'){
            htmlFromObj += '<label>' + key + '</label></br><input  type="text" value="'+ value +'" id="' + key + '">' + '</br>';
        }
    });
    target.insertAdjacentHTML('beforeend', htmlFromObj);
    modal.show();
}

问题原因及解决方案

原因分析

  1. 未清空Modal原有内容:每次调用函数时,会在初始的<p>Modal body text goes here.</p>后追加新HTML,若多次调用会导致内容冗余,且可能因意外情况混入undefined文本。
  2. 遍历无关属性:Object.entries(formData)会遍历对象所有属性(如createdBy、_links等),虽然未拼接这些属性的HTML,但增加了潜在出错风险;同时多个else if的写法不够健壮,若属性缺失会直接跳过,可能导致逻辑漏洞。

修复后的代码

function myEditObjIterFunction(formData) {
    let modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('myModal'));
    const target = document.querySelector("#modalBody");
    // 清空Modal原有内容,避免重复或冗余文本
    target.innerHTML = '';
    const htmlSegments = [];
    // 定义需要生成输入框的目标属性列表,避免遍历无关属性
    const targetKeys = ['softwarename', 'softwareprovider', 'softwareprovidercontactemail'];
    
    targetKeys.forEach(key => {
        // 确保属性值不存在时显示空字符串,而非undefined
        const value = formData[key] || '';
        // 使用模板字符串拼接HTML,更易读且避免语法错误
        htmlSegments.push(`<label>${key}</label><br><input type="text" value="${value}" id="${key}"><br>`);
    });
    
    // 拼接所有HTML片段并插入到Modal中
    target.insertAdjacentHTML('beforeend', htmlSegments.join(''));
    modal.show();
}

优化点说明

  • 提前清空modalBody内容,彻底避免初始文本或重复内容的干扰。
  • 直接遍历目标属性列表,无需处理无关属性,代码更简洁高效。
  • 使用formData[key] || ''兜底,确保属性值缺失时输入框不会显示undefined。
  • 用数组存储HTML片段再拼接,比字符串累加的性能更好,也更易维护。
  • 替换不规范的</br>为标准换行标签<br>。

内容的提问来源于stack exchange,提问作者Ajay Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:35:04