How to take out the commas and insert spaces between the numbers in this array?

Asked

Viewed 222 times

1

I made this array but I can’t get the commas out and swap them out for two or three spaces. Someone has 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

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

2 answers

2

To join an array into a string use the function join passing the character that will be used between the elements:

[1, 2, 3].join(' ');

1


Use the function join(caracterSeparador) 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 function join:

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

How you are using the function document.write the content will be written in HTML, for this reason the blank is the character &nbsp;.

  • Thanks but I only managed to put 1 space.. I can’t get 2 or 3 spaces?

  • Try again, with this response change.

  • Exactly. That’s right. I’m very grateful.

  • If the answer helped you and can help other people please mark it as accepted answer please. Thank you :D

  • OK.. I clicked on the check mark and went to green color.

  • Thank you very much!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.