skip to Main Content

I made a Random numbers with math.random();

but they have , between like :

5,7,8,10

How can I write Space between Characters with Javascript?

like this:
5 7 8 10

I’m sorry! My English is very poor.

All my code is here:

let numbers = [
  Math.round(Math.random() * 100 - 1 + 1),
  Math.round(Math.random() * 100 - 1 + 1),
  Math.round(Math.random() * 100 - 1 + 1),
  Math.round(Math.random() * 100 - 1 + 1),
  Math.round(Math.random() * 100 - 1 + 1),
  Math.round(Math.random() * 100 - 1 + 1),
  Math.round(Math.random() * 100 - 1 + 1),
];
console.log(numbers);
let evenNumbersArray = [];
let evenNumbers = numbers.forEach(function (number) {
  if (number % 2 === 0) {
    console.log(number);
    evenNumbersArray.push(number);
  }
});
evenNumbersArray.toString();
document.getElementById(
  "showEvenNumbers"
).innerText = `Our evenNumbers are :  ${evenNumbersArray}`;

2

Answers


  1. To remove ‘,’ and replace them with space character, you should use replaceAll method on the string.
    In another words, You convert your array to string with .toString() method, then use .replaceAll('a', 'b') to replace a with b in whole string.

    More info about replace and replaceAll method: https://www.w3schools.com/jsref/jsref_replace.asp

    const numbers = [
      Math.round(Math.random() * 100 - 1 + 1),
      Math.round(Math.random() * 100 - 1 + 1),
      Math.round(Math.random() * 100 - 1 + 1),
      Math.round(Math.random() * 100 - 1 + 1),
      Math.round(Math.random() * 100 - 1 + 1),
      Math.round(Math.random() * 100 - 1 + 1),
      Math.round(Math.random() * 100 - 1 + 1),
    ];
    
    const evenNumbersArray = [];
    numbers.forEach(function (number) {
      if (number % 2 === 0) {
        evenNumbersArray.push(number);
      }
    });
    
    const text = evenNumbersArray.toString().replaceAll(',',' ');
    
    // then add text to DOM:
    document.getElementById("showEvenNumbers").innerText = `Our evenNumbers are :  ${text}`;
    <p id="showEvenNumbers"></p>
    Login or Signup to reply.
  2. I think this is a better way to do this :

    // Specify the length of the array
    const length = 10;
    
    // Specify the minimum and maximum values
    const min = 1;
    const max = 100;
    
    // Generate a random number between min and max (inclusive)
    const randomNumber = () => Math.floor(Math.random() * (max - min + 1)) + min;
    
    
    // Create an array filled with random numbers
    const numbers = Array.from({ length }, randomNumber);
    
    // Print the array contents separated by whitespace
    console.log(numbers.join(' '));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search