模板文字中包含ForEach [英] Template Literals with a ForEach in it

查看:180
本文介绍了模板文字中包含ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在模板文字中的 ForEach 中返回字符串值,以便将其添加到该位置?因为如果我记录它,它返回 undefined 。或者就像我输入的那样根本不可能?

Is it possible to return a string value in ForEach in a Template literal so it will be added in that place? Because if I log it it returns undefined. Or is that like I typed not possible at all?

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).forEach(function (key) {
        return "<option value='" + key + "'>" + obj[key] + "</option>"           
    })}
    `;


推荐答案

不,因为 forEach 忽略其回调的返回值,并且永远不会返回任何内容(因此,调用它会导致 undefined )。

No, because forEach ignores the return value of its callback and never returns anything (thus, calling it results in undefined).

您正在寻找 地图 完全您想要的内容:

You're looking for map, which does exactly what you want:

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("")}
    `;

请注意,映射后,代码使用 .join()从数组中获取单个字符串(没有任何分隔符)。 (我最初忘记了这一点—做了太多React的事情 —但 stephledev 指出了这一点他/她的回答。)

Note that after mapping, the code uses .join("") to get a single string from the array (without any delimiter). (I forgot this initially — been doing too much React stuff — but stephledev pointed it out in his/her answer.)

旁注:这不是字符串文字,而是 template literal

Side note: That's not a "string literal," it's a template literal.

这篇关于模板文字中包含ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆