简体   繁体   English

JS:如何在循环中将数组随机化,但每个值只能选择一次?

[英]JS: How to randomize an array in a loop yet only allow each value to be selected once?

That's a mouthful. 满嘴

Basically I have a loop and am assigning a unique number between 1 & 4 to an array value. 基本上,我有一个循环,正在为数组值分配1和4之间的唯一数字。 This loop runs 4 times and each time there should be one less choice due to already being used in the previous cycle. 该循环运行4次,由于上一循环已使用过,因此每次应少选择一个。

Here is a js fiddle: https://jsfiddle.net/jtree5757/mh3okwaj/ 这是一个JS小提琴: https : //jsfiddle.net/jtree5757/mh3okwaj/

And here is some code: 这是一些代码:

var employee_name = document.getElementsByClassName("employee-name");
var masterArray = [];

var numbersArr = [1, 2, 3, 4];
var random = numbersArr.splice(Math.random()*numbersArr.length,1)[0];

for(i=0; i < employee_name.length; i++){
    masterArray.push({
        name: employee_name[i].innerText,
        shift: random
    });
}

This outputs the same number for each cycle of the loop. 对于循环的每个循环,这将输出相同的数字。 Not sure where to go on this one. 不知道该去哪里。

var random = numbersArr.splice(Math.random()*numbersArr.length,1)[0];

This piece of code should be in your for loop. 这段代码应该在您的for循环中。 That way on each iteration new value will be generated. 这样,每次迭代都会生成新值。

You can see the updated fiddle. 您可以看到更新的小提琴。

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

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