简体   繁体   中英

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. This loop runs 4 times and each time there should be one less choice due to already being used in the previous cycle.

Here is a js fiddle: 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. That way on each iteration new value will be generated.

You can see the updated fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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