Generate array with random values in Javascript

Asked

Viewed 2,961 times

2

I want to generate an array with 10 type positions: var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

But I wanted the computer to choose 10 numbers from -9 to 9, to put inside this array.

2 answers

10

You can use the MDN function Math. to generate random numbers with interval:

Math.floor(Math.random() * (max - min + 1)) + min;

Example

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

let array = [];
for (let i = 0 ; i < 10 ; i++){
  array.push(getRandom(-9,9));
}

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Where floor is applied to obtain an integer.

-2

for a more readable code, you can use the above solution, but if you want a smaller code, you can use this one

// [...Array(10)] gera um array com 10 undefineds
// .map() vai preencher todos os elementos do array de acordo com uma função
// ()=>Math.random()*18-9   é a função que retorna um número aleatório entre -9 e 9 (se você quiser inteiros use ()=>Math.floor(Math.random()*19-9))
var array = [...Array(10)].map(()=>Math.random()*18-9);

console.log(array);

Browser other questions tagged

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