简体   繁体   English

从数组中选择随机值并创建新数组

[英]Picking random values from array and creating new array

I have an array, and need to pick three random values from that array. 我有一个数组,需要从该数组中选择三个随机值。 These will the be put in a new array and I will be able to see the new array on my website. 这些将被放入一个新的阵列中,我将能够在我的网站上看到该新阵列。 I also have to make sure that no value gets picked twice. 我还必须确保没有值被两次选择。

This is what I have so far: 这是我到目前为止的内容:

 var student = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
 var velg = student[Math.floor(Math.random() * student.length)];

I'm thinking I should add an id to my HTML, so the new array will show on my website, but I'm not sure about the rest. 我想我应该在HTML中添加一个id,这样新的数组就会显示在我的网站上,但是我不确定其余的内容。

First sort it randomly and then get first three: 首先将其随机排序,然后得到前三个:

student
   .sort(function(){
       return Math.random() - 0.5;
     })
   .slice(0,3)

Since Math.random() returns random value between 0 and 1, while sort expects values to be positive or negative to determine order we, we need to subtract 0.5 to make those negatives possible. 由于Math.random()返回0到1之间的随机值,而sort期望值是正数或负数来确定我们的阶数,因此我们需要减去0.5以使这些负数成为可能。

You could try something like this in a loop 您可以循环尝试这样的事情

var students = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
var randomStudents = [];
for(var i = 0; i < 3; i++) {
    var velg = student[Math.floor(Math.random() * students.length)];
    randomStudents.push(velg);
}

Note that this can add duplicate students to the array. 请注意,这可以将重复的学生添加到数组中。 You should check if student is already in the array and try again. 您应该检查学生是否已经在数组中,然后重试。

Keyword for that would be recursion. 关键字是递归。

https://www.codecademy.com/courses/javascript-lesson-205/0/1 https://www.codecademy.com/courses/javascript-lesson-205/0/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM