javascript 带有 ForEach 的模板文字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48368299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:59:46  来源:igfitidea点击:

Template Literals with a ForEach in it

javascriptjquerystringtemplate-literals

提问by Steven

Is it possible to return a string value in ForEachin 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?

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

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

回答by T.J. Crowder

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

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

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

您正在寻找map,这正是您想要的:

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 stephledevpointed it out in his/her answer.)

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



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

旁注:这不是“字符串文字”,而是模板文字

回答by stephledev

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:

由于map()返回一个数组,@TJ Crowder 的回答将产生无效的 HTML,因为toString()将在模板文字中调用数组的方法,该方法使用逗号分隔数组。要解决此问题,只需附加join('')以明确不使用分隔符:

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

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

此外,您可以在地图本身内使用模板文字。