我想创建一个项目列表,其中随机选择项目,并从不同的组中选择每个项目。我对此非常陌生,但这段代码似乎也是这样。
<html>
<body>
<p>Random items from three different groups:</p>
<script type="text/javascript">
<!--
document.write('<ol>');
// first group
var first_group = new Array ();
first_group[0] = "one";
first_group[1] = "two";
first_group[2] = "three";
var i = Math.floor(3*Math.random())
document.write('<li>' + first_group[i]);
// second group
var second_group = new Array ();
second_group[0] = "three";
second_group[1] = "four";
second_group[2] = "five";
var i = Math.floor(3*Math.random())
document.write('<li>' + second_group[i]);
// third group
var third_group = new Array ();
third_group[0] = "five";
third_group[1] = "six";
third_group[2] = "seven";
var i = Math.floor(3*Math.random())
document.write('<li>' + third_group[i]);
document.write('</ol>');
//-->
</script>
</body>
</html>
是否可以修改代码,以便即使相同的项目出现在多个组中,同一项目也不会在最终列表中出现多次? (例如,如果从第一组中选择“三”,则无法从第二组中选择。)并且是否可以按随机顺序排列最终列表?任何有关其他改进的建议也是受欢迎的。
答案 0 :(得分:1)
试试这个:
<html>
<body>
<p>Random items from three different groups:</p>
<script type="text/javascript">
var selectedValues = [];
function chooseRandom(array) {
// Select random number until it's a number that wasn't selected yet
do {
var random = Math.floor(array.length * Math.random());
var randomResult = array[random];
} while (selectedValues.indexOf(randomResult) > -1)
// Log the selected number so it won't be selected randomly again
selectedValues.push(randomResult);
return randomResult;
}
document.write('<ol>');
var first_group = ["one", "two", "three"];
var second_group = ["three", "four", "five"];
var third_group = ["five", "six", "seven"];
document.write('<li>' + chooseRandom(first_group) + '</li>');
document.write('<li>' + chooseRandom(second_group) + '</li>');
document.write('<li>' + chooseRandom(third_group) + '</li>');
// Finalize
document.write('</ol>');
</script>
</body>
</html>
答案 1 :(得分:1)
使用自定义JavaScript函数是最好的方法。根据您的示例(您可能需要扩展到更复杂的生态系统:
<script type="text/javascript">
<!--
var i=j=k=x=0;
var first_group = ["one", "two", "three"];
var second_group = ["three", "four", "five"];
var third_group = ["five", "six", "seven"];
i = Math.floor(3*Math.random());
j = Math.floor(3*Math.random());
k = Math.floor(3*Math.random());
var okayArray=makeNoDup(first_group,i,second_group,j,third_group,k);
document.write('<ol>');
okayArray.forEach(function(e) {
document.write('<li>' + e[x] + '</li>');
x++;
}
document.write('</ol>');
function makeNoDup(first,i,second,j,third,k){
if(first[i] === second[j]){
var newj = Math.floor(3*Math.random());
j= makeNoDup(first, i, second, newj, third, k);
}
if(first[i] === third[K] || second[j] === third[k]){
var newK = Math.floor(3*Math.random());
k= makeNoDup(first, i, second, j, third, newk);
}
var answer = {
first: i,
second: j,
third: k
};
return (answer);
}
//-->
</script>
关键是递归函数makeNoDup
。