JavaScript随机排序算法1
1.对数组循环,每一项与随机的某一项位置调换
<ul id="listOne"></ul> <div id="tempOne"></div> <script type="text/javascript"> var listOne = $('#listOne'); var numberList = []; //项ul中添加 10个数字 for (var i = 0; i < 10; i++) { listOne.append('<li>' + i + '</li>'); numberList.push(i); } //随机排序 for (var i = 0; i < 10; i++) { var random = Math.floor(Math.random() * 10); //顺序调换 var temp = numberList[i]; numberList[i] = numberList[random]; numberList[random] = temp; } $('#tempOne').html(numberList); </script>
显示结果:
2.Dom结构中的元素随机排序方法
<ul id="listOne"></ul> <script type="text/javascript"> var listOne = $('#listOne'); //项ul中添加 10个数字 for (var i = 0; i < 10; i++) { listOne.append('<li>' + i + '</li>'); } //获取li集合的备份 var liList = listOne.children().clone(); //随机调换顺序 for (var i = 0; i < liList.length; i++) { var random = Math.floor(Math.random() * liList.length); //位置调换 var temp = liList[i]; liList[i] = liList[random]; liList[random] = temp; } listOne.empty().append(liList); </script>