Generate array with random values in Javascript

2

I want to generate an array with 10 positions type: 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 that array.

    
asked by anonymous 29.12.2017 / 13:39

1 answer

8

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

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 get an integer.

    
29.12.2017 / 13:45