[JS an array randomly selects x elements]

You can use the Math.random() method, combined with a loop and the splice() method:

let arr = [1,2,3,4,5,6,7,8,9];
let randomArr = [];

for(let i = 0; i < 4; i++) {
    
    
  let randomIndex = Math.floor(Math.random() * arr.length);
  let randomNum = arr.splice(randomIndex, 1)[0];
  randomArr.push(randomNum);
}

console.log(randomArr); // 输出随机选取的四个元素的数组

To explain the code:

  1. Define an original array arr and an empty array randomArr to store four randomly selected elements;
  2. Use the for loop to loop four times, each time selecting a random number;
  3. Use the Math.random() method to generate a random number from 0 to 1, and then multiply it by the length of the array to get a random integer between 0 and the length of the array. Use the Math.floor() method to round to get a random array. mark randomIndex;
  4. Use the splice() method to delete the element whose random index is randomIndex from the original array arr, return the element, and assign it to the variable randomNum;
  5. Add the variable randomNum to the random array randomArr;
  6. After the loop is completed, the random array randomArr contains four randomly selected elements.

Guess you like

Origin blog.csdn.net/Ge_Daye/article/details/132208072