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

在JavaScript中如何将undefined值替换为空字符串

问题原因

你的代码存在两处核心逻辑错误:

  • 条件判断逻辑完全倒置:你初始化year为空字符串后,反而在product.year === undefined的情况下把year赋值为undefined,和预期需求完全相反
  • 自行定义的year变量没有实际使用:模板字符串渲染年份时依然直接调用了原始的product.year,自然会输出undefined

修复方案

方案1:修正原有逻辑

调整判断条件,同时把模板里的年份替换成你定义的year变量即可:

product.photos.map(() => {
    let year = "";
    // 只有年份存在时才赋值,否则保持初始空字符串
    if (product.year !== undefined) {
        year = product.year;
    }
    // Then output the data
    output += `
            <div class="card">
              <img class="img-fluid" src="${product.photos[0].text}" alt="${product.model}" />
              <h3>${year} ${product.manufacturer} ${product.model}</h3>
              <p>${product.hours} hours</p>
              <a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product["serial-number"]}' class="btn btn-primary">View Details</a>
            </div>         
        `;
});

方案2:更简洁的空值合并写法

不需要单独定义year变量,直接在模板中用空值合并运算符??处理即可,代码更精简:

product.photos.map(() => {
    output += `
            <div class="card">
              <img class="img-fluid" src="${product.photos[0].text}" alt="${product.model}" />
              <h3>${product.year ?? ''} ${product.manufacturer} ${product.model}</h3>
              <p>${product.hours} hours</p>
              <a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product["serial-number"]}' class="btn btn-primary">View Details</a>
            </div>         
        `;
});

额外提示:上述代码给img标签的src和alt属性补充了双引号,避免属性值包含空格时出现HTML解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:24:03