これが良いなー
<body>
<li> 1. <span id="010"></span> </li>
<li> 2. <span id="009"></span> </li>
<li> 3. <span id="008"></span> </li>
<li> 4. <span id="007"></span> </li>
<li> 5. <span id="006"></span> </li>
<li> 6. <span id="005"></span> </li>
<li> 7. <span id="004"></span> </li>
<li> 8. <span id="003"></span> </li>
<li> 9. <span id="002"></span> </li>
<li> 10. <span id="001"></span> </li>
<script type="text/javascript">
var array = [1,2,3,4,5,6,7,8,9,10];
function run(){
for (var i = array.length-1 ; i >=0 ; i--){
var rand = Math.floor(Math.random()*(i+1));
var temp = array[i];
array[i] = array[rand];
array[rand] = temp;
document.getElementById("00"+i).innerHTML = i +"回目 = " + array;
}
}
run();
<script>
</body>
2. これは良さそうだけど、理解できない。
https://h2ham.net/javascript-random-array
function random(array, num) {
var a = array;
var t = [];
var r = [];
var l = a.length;
var n = num < l ? num : l;
while (n-- > 0) {
var i = Math.random() * l | 0;
r[n] = t[i] || a[i];
--l;
t[i] = t[l] || a[l];
}
return r;
}
var test_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
random(test_array, 5);
0 件のコメント:
コメントを投稿