Template Literals with a ForEach in it

风流意气都作罢 提交于 2019-12-22 03:24:08

问题


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

回答1:


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

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.)


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




回答2:


Since map() returns an array, @T.J. Crowder's answer will produce invalid HTML as the toString() method of an array will be called inside the template literal, which uses commas to delimit the array. To fix this, just append join('') to explicitly use no delimiter:

${Object.keys(obj).map(key => (
    `<option value="${key}">${obj[key]}</option>`
)).join('')}

Also, you can use template literals inside the map itself.



来源:https://stackoverflow.com/questions/48368299/template-literals-with-a-foreach-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!