问题描述
我正在一个项目中,我需要生成一个数组的十六个随机元素。我需要确保随机数中的两个恰好是给定的元素,但是我不希望它们每次都位于同一位置。有没有一种方法可以从数组中生成随机项目,但是可以保证其中两个随机项目将成为特定元素?
<div id = "choice1">
<div id = "choice2">
<div id = "choice3">
<div id = "choice4">
<div id = "choice5">
<div id = "choice6">
<div id = "choice7">
<div id = "choice8">
<div id = "choice9">
<div id = "choice10">
<div id = "choice11">
<div id = "choice12">
<div id = "choice13">
<div id = "choice14">
<div id = "choice15">
<div id = "choice16">
var elem = ["a","b","c","d"...];
var o1 = Math.floor(Math.random() * elem.length);
var obj1 = elem[o1];
document.getElementById("choice1").innerHTML = obj1;
...
解决方法
您可以像这样(从this post改编而来)在普通JavaScript中执行此操作:
//"pre-select" required elements
var selectedElementIDs = ["choice1","choice2"];
//define other possible elements
var otherPossibleElementIDs = ["choice3","choice4","choice5","choice6","choice7","choice8","choice9","choice10","choice11","choice12","choice13","choice14","choice15","choice16"];
//"select" 3 more elements from the "possible elements" array
for (var i = 0; i < 3; i++) selectedElementIDs.push(otherPossibleElementIDs.splice(Math.floor(Math.random() * otherPossibleElementIDs.length),1)[0]);
//shuffle your selections so the "pre-selected" required elements aren't always first
var j,x,i;
for (i = selectedElementIDs.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = selectedElementIDs[i];
selectedElementIDs[i] = selectedElementIDs[j];
selectedElementIDs[j] = x;
}
//log the result to the console to show it worked
console.log(selectedElementIDs);
或者,如果愿意,您可以使用rando.js以更易于理解(且加密安全)的方式进行此操作:
//"pre-select" required elements
var selectedElementIDs = ["choice1","choice2"];
//define other possible elements (and go ahead and shuffle them so "popping" from that array after this will produce a random next value)
var otherPossibleElementIDs = randoSequence(["choice3","choice16"]);
//"select" 3 more elements from the "possible elements" array
for(var i = 0; i < 3; i++) selectedElementIDs.push(otherPossibleElementIDs.pop().value);
//shuffle your selections so the "pre-selected" required elements aren't always first
selectedElementIDs = randoSequence(selectedElementIDs);
for(var i = 0; i < selectedElementIDs.length; i++) selectedElementIDs[i] = selectedElementIDs[i].value;
//log the result to the console to show it worked
console.log(selectedElementIDs);
<script src="https://randojs.com/2.0.0.js"></script>