当我在模板文字中使用 .map 时,为什么我的输出中有逗号?

我有这样的变量和循环:


var htmlmask = `

<table>

    <tr>

        <td>種類</td>

        <td>

            <div class="form-element maskselectop">

                <select class="form-element">

                    ${masktypes.map((masktype, i)=>{

                        let option = '';

                        return option = `<option value="${masktype}" ${(i === 0) ? 'selected' : ''}>${masktype}</option>`;

                    })}

                </select>

            </div>

        </td>

    </tr>

  </table>`;


$('body').html(htmlmask);

你能告诉我为什么在返回后comma出现option?

http://img1.mukewang.com/635a22fc0001a6fe04270123.jpg

我的语法有什么问题?



慕运维8079593
浏览 284回答 2
2回答

茅侃侃

因为Array.prototype.map函数返回一个新数组。当您将数组连接到字符串时,数组也会转换为字符串。并且当数组转换为字符串时,它用逗号分隔。const&nbsp;arr&nbsp;=&nbsp;['<a>',&nbsp;'<b>'];&nbsp;&nbsp; console.log(arr.toString());&nbsp;//&nbsp;<a>,<b>我会使用该Array.prototype.reduce函数将数组减少为单个字符串。masktypes.reduce((acc,&nbsp;masktype,&nbsp;i)&nbsp;=>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;acc&nbsp;+&nbsp;`<option&nbsp;value="${masktype}"&nbsp;${(i&nbsp;===&nbsp;0)&nbsp;?&nbsp;'selected'&nbsp;:&nbsp;''}>${masktype}</option>`,&nbsp;'')所以完整的代码会变成:const masktypes = ["1", "2"];var htmlmask = `&nbsp; &nbsp; <table>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>種類</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="form-element maskselectop">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <select class="form-element">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ${masktypes.reduce((acc, masktype, i) =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; acc + `<option value="${masktype}" ${(i === 0) ? 'selected' : ''}>${masktype}</option>`, '')}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </select>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; </table>`;$('body').html(htmlmask);<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

蛊毒传说

它使您的元素数组成为字符串。利用<select class="form-element">&nbsp; &nbsp; ${masktypes.map((masktype, i)=>{&nbsp; &nbsp; &nbsp; &nbsp; let option = '';&nbsp; &nbsp; &nbsp; &nbsp; return option = `<option value="${masktype}" ${(i === 0) ? 'selected' : ''}>${masktype}</option>`;&nbsp; &nbsp; }).join("")}</select>只需添加.join(""),它就会加入没有逗号。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript