6

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?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Hai Tien
  • 2,929
  • 7
  • 36
  • 55

2 Answers2

9

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.

Ivar
  • 6,138
  • 12
  • 49
  • 61
Satpal Tanan
  • 1,108
  • 7
  • 17
7

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>
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • Small note, I intended to delete this answer after I found a [very similar question](https://stackoverflow.com/questions/45812160/unexpected-comma-using-map) so I could answer it there instead. (To keep all the useful information in one place.) Unfortunately due to this answer being accepted, I cannot delete it. – Ivar Jul 02 '20 at 08:23