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:
- Define an original array arr and an empty array randomArr to store four randomly selected elements;
- Use the for loop to loop four times, each time selecting a random number;
- 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;
- 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;
- Add the variable randomNum to the random array randomArr;
- After the loop is completed, the random array randomArr contains four randomly selected elements.