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

在模板字面量中使用forEach能否返回字符串并插入对应位置?

问题解答:模板字面量中使用forEach返回字符串的问题

嘿,这个问题我之前踩过坑!你遇到的undefined问题,根源在于forEach方法的特性——它本身没有返回值(默认返回undefined),不管你在回调函数里写多少return,它都不会收集这些返回结果,执行完就结束了,所以模板字面量里插入的自然就是它的返回值undefined。

正确的解决方案:用map替代forEach

map方法会遍历数组,把每个元素经过回调处理后的返回值收集成一个新数组,之后我们只需要用join('')把数组拼接成完整的字符串,就能完美插入到模板里了。

修改你的代码如下:

return `<div> 
  <form id='changeExchangeForViewing'> 
    <label for='choiceExchangeForLoading'>Change the exchange</label> 
    <div class='form-inline'> 
      <select id='choiceExchangeForLoading' name='choiceExchangeForLoading' class='form-control'> 
        ${Object.keys(obj).map(function (key) { 
          return "<option value='" + key + "'>" + obj[key] + "</option>" 
        }).join('')} 
      </select>
    </div>
  </form>
</div>`;

如果想让代码更简洁,还可以用箭头函数配合模板字面量的嵌套:

return `<div> 
  <form id='changeExchangeForViewing'> 
    <label for='choiceExchangeForLoading'>Change the exchange</label> 
    <div class='form-inline'> 
      <select id='choiceExchangeForLoading' name='choiceExchangeForLoading' class='form-control'> 
        ${Object.keys(obj).map(key => `<option value='${key}'>${obj[key]}</option>`).join('')} 
      </select>
    </div>
  </form>
</div>`;

补充说明

  • forEach适合那些只需要遍历执行操作、不需要收集结果的场景(比如修改原数组元素、打印内容等)。
  • 如果你的obj里可能存在null或undefined类型的值,还可以先加一层过滤,避免生成空的option:
    ${Object.keys(obj)
      .filter(key => obj[key] != null)
      .map(key => `<option value='${key}'>${obj[key]}</option>`)
      .join('')}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:34:57