我想创建一个项目列表,其中的项目是随机选择的,每个项目都是从不同的组中选择的。我对此很陌生,但这段代码似乎可以做到这一点。
<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>
是否可以修改代码,使即使相同的项目出现在多个组中,相同的项目也不能在最终列表中出现多次? (例如,如果从第一组中选择“三”,则不能从第二组中选择。)最后的列表是否可以随机排序?也欢迎任何其他改进建议。
最佳答案
试试这个:
<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>
关于javascript - 随机选择的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41449804/