generate a random array in javascript

To generate a random array in JavaScript, you can use the Math.random() method to generate random numbers and add them to an array. Here's an example code snippet:

index.tsx
function generateRandomArray(length, max) {
  var arr = [];
  for (var i = 0; i < length; i++) {
    arr.push(Math.floor(Math.random() * max));
  }
  return arr;
}

// Example usage:
var randomArray = generateRandomArray(10, 100);
console.log(randomArray); // output: [67, 41, 25, 83, 91, 3, 90, 20, 35, 78]
308 chars
12 lines

In this function, length is the desired length of the array and max is the maximum value for the random numbers that the function generates. The Math.floor() method rounds the random number down to the nearest integer, ensuring that the array only contains integers. The loop runs length number of times, pushing a new random number to the array on each iteration. Finally, the function returns the generated array.

gistlibby LogSnag