JS implements random selection of 4 students

Randomly select 4 members of the array to form a new array

4 students will be randomly selected from the following list of students:

 var arr = ["Luhan", "Wang Junkai", "Cai Xukun", "Eddie Peng", "Jay Chou", "Andy Lau", "Zhao Benshan"];

// Note: Do not have duplicate students

Idea: Randomly generate a number within the index range of the arr array, use the array to remove duplicates to eliminate the possibility of repetition, and loop 4 times to output

<script>
var arr = ["鹿晗", "王俊凯", "蔡徐坤", "彭于晏", "周杰伦", "刘德华", "赵本山"];
var newArr = [];
while (newArr.length < 4) {
function getRandomIntInclusive(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
var i = getRandomIntInclusive(0, 6);// 随机生成0-6之间的一个数,作为数组索引
if (newArr.indexOf(arr[i]) === -1) {  // 题目要求不能有重复,故用数组去重思路
      newArr.push(arr[i]);
  }
}
console.log(newArr);
</script>

Guess you like

Origin blog.csdn.net/weixin_44566194/article/details/126456570