How do I get the commas and insert spaces between the numbers in this array?

0

I made this array but I can not get the commas out and replace them with two or three spaces. Does anyone have an idea to help me please?

<div id="demo1" name="demo1" style="margin-left: 100px; margin-top:25px;color:red; font-size:16px; font-weight:bold;  letter-spacing: 00px;">   
<script>

var arr = []
while(arr.length < 4){
    var r = Math.floor(Math.random()*16) + 1;
    if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);

</script>
</div>

EXAMPLE OF THE RESULT: 3,12,9,7

RESULT INTENDED FOR 1 OR MORE SPACES: 3 12 9 7

    
asked by anonymous 03.01.2019 / 11:56

2 answers

1

Use the join(caracterSeparador) function to add the separator character between each array item.

Example:

var arr = [];

while (arr.length < 4) {
    var r = Math.floor(Math.random()*16) + 1;

    if (arr.indexOf(r) === -1) 
        arr.push(r);
}

// 1 espaço em branco
document.write(arr.join('&nbsp;'));

If you want 3 spaces, just put as a parameter in the join function:

// 3 espaços em branco
document.write(arr.join('&nbsp;&nbsp;&nbsp;'));

Since you are using the document.write function, the content will be written to the HTML, so whitespace is the &nbsp; character.

    
03.01.2019 / 12:05
2

For unirum array in a string use the function join passing the character that will be used between the elements:

[1, 2, 3].join(' ');
    
03.01.2019 / 12:05