要使JavaScript数组随机显示随机元素,可以尝试运行以下代码:
<html> <body> <script> function randomFunc(myArr) { var l = myArr.length, temp, index; while (l > 0) { index = Math.floor(Math.random() * l); l--; temp = myArr[l]; myArr[l] = myArr[index]; myArr[index] = temp; } return myArr; } var arr = [10, 20, 30, 40, 50]; document.write(randomFunc(arr)); </script> </body> </html>
输出结果
20,50,40,30,10