我有一个20号阵列。现在我挑选(随机)其中5个,我想把它们放入另一个空阵列。我能怎么做?而且,当它们显示时,如何将它们隐藏在第一个数组中?谢谢大家。
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var randomNumbers = document.getElementById("demo");
randomNumbers.innerHTML = tenNumbers[Math.floor(Math.random()*tenNumbers.length)];
答案 0 :(得分:4)
好像你应该能够使用splice从原始数组中删除一个随机元素,然后将该结果推送到一个新数组:
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var outArray = [];
for(var i=0; i<5; i++) {
outArray.push(tenNumbers.splice(Math.floor(Math.random()*tenNumbers.length), 1)[0]);
}
document.write(outArray + "<br />" + tenNumbers);
&#13;
答案 1 :(得分:2)
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var randomNumbersArray = [];
for (var i = 0; i < 5; i++)
{
randomNumbersArray.push(tenNumbers.splice(Math.floor(Math.random()*tenNumbers.length), 1));
}
document.getElementById("random").innerHTML = randomNumbersArray.join("<br />");
<div id="random"></div>
这应该这样做。
答案 2 :(得分:0)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var tenNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 42, 178, 54, 76, 32, 12, 38, 154, 234];
var randNums = [];
var randomNumbers = document.getElementById("demo");
for(var i = 0; i < 5; i++)
{
var index = getRandomInt(0, tenNumbers.length - 1);
randNums.push(tenNumbers[index]);
randomNumbers.innerHTML += tenNumbers[index] + ", ";
tenNumbers.splice(index, 1);
}
<div id="demo">
</div>
答案 3 :(得分:0)
您还可以选择5个随机元素,然后使用.sort
&amp;将它们移动到新数组中。 .splice
单行:
var outArray = tenNumbers.sort(function(){ return Math.random() - 0.5; }).splice(0,5);