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

使用insertAdjacentHTML循环渲染礼物时出现多余逗号,如何解决?

问题:循环渲染礼物列表出现多余逗号怎么解决?

尝试循环渲染礼物列表时,每次循环后insertAdjacentHTML会插入多余的逗号,相关代码如下:

document.querySelector(`.chat-content`)?.insertAdjacentHTML(
  'beforeend',
  `<div class="gifts flex items-center h-20 gap-2">
        ${gifts.map((gift: any) => `
            <div class="gift bg-skin-field text-primary-yellow">
                <i class="fas fa-gift"></i>
                <span class="text-gray-400">${gift.channelId}</span>
                <span>$${gift.price}</span>
            </div>
            `,
    )}
    </div>`,
)

问题现象:
循环渲染后出现多余逗号的效果


解决方案

出现多余逗号的核心原因:map方法返回的是数组,当在模板字符串中直接使用数组时,JavaScript会自动调用数组的toString()方法,将数组元素用逗号连接后输出。

以下两种方法可解决该问题:

方法1:给map结果添加.join('')

在map调用后追加.join(''),将数组转换为无分隔符的字符串:

document.querySelector(`.chat-content`)?.insertAdjacentHTML(
  'beforeend',
  `<div class="gifts flex items-center h-20 gap-2">
        ${gifts.map((gift: any) => `
            <div class="gift bg-skin-field text-primary-yellow">
                <i class="fas fa-gift"></i>
                <span class="text-gray-400">${gift.channelId}</span>
                <span>$${gift.price}</span>
            </div>
            `).join('')}
    </div>`,
)

方法2:使用reduce替代map

用reduce直接拼接字符串,从根源避免生成数组:

document.querySelector(`.chat-content`)?.insertAdjacentHTML(
  'beforeend',
  `<div class="gifts flex items-center h-20 gap-2">
        ${gifts.reduce((html: string, gift: any) => html + `
            <div class="gift bg-skin-field text-primary-yellow">
                <i class="fas fa-gift"></i>
                <span class="text-gray-400">${gift.channelId}</span>
                <span>$${gift.price}</span>
            </div>
            `, '')}
    </div>`,
)

内容的提问来源于stack exchange,提问作者Anik Ahmed fathe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:48:59