Why are there comma's in my output when I use .map in a template literal?

Viewed 345

I have variable and loop inside like this:

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

Can you tell me why the comma appears between option after return?

enter image description here

What wrong with my syntax?

2 Answers

Because the Array.prototype.map function returns a new array. And when you concatenate an array to a string, the array is converted into a string as well. And when an array is converted to a string, it is separated by comma's.

const arr = ['<a>', '<b>'];

console.log(arr.toString()); // <a>,<b>

I would use the Array.prototype.reduce function to reduce the array into a single string.

masktypes.reduce((acc, masktype, i) => 
    acc + `<option value="${masktype}" ${(i === 0) ? 'selected' : ''}>${masktype}</option>`, '')

So the complete code would become:

const masktypes = ["1", "2"];

var htmlmask = `
    <table>
        <tr>
            <td>種類</td>
            <td>
                <div class="form-element maskselectop">
                    <select class="form-element">
                        ${masktypes.reduce((acc, masktype, i) => 
                            acc + `<option value="${masktype}" ${(i === 0) ? 'selected' : ''}>${masktype}</option>`, '')}
                    </select>
                </div>
            </td>
        </tr>
      </table>`;

$('body').html(htmlmask);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

It is making your array of elements as strings. Use

<select class="form-element">
    ${masktypes.map((masktype, i)=>{
        let option = '';
        return option = `<option value="${masktype}" ${(i === 0) ? 'selected' : ''}>${masktype}</option>`;
    }).join("")}
</select>

Just add .join("") and it would join without the commas.

Related