自定义shuffle打乱JS数组次序


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script>
var aray=new Array(
    'wa','wai','wan','wang','wei','wen','weng','wo','wu'
);

function shuffle(a){
    var len=a.length;
    var index=0;
    var temp=0;
    for (var i=0; i<len-1; i++){
        index=parseInt(Math.random() * (len-i));
        temp=a[index];
        a[index]=a[len-i-1];
        a[len-i-1]=temp;
    }
}

function rnd(a){
    shuffle(a);
    var temp='';
    for(var i=0;i<a.length;i++){
        temp += (a[i]+",");
    }
    form1.content.value = temp;
}

</script>

<form name="form1">
<input name="content" type="text" style="width:100%;">
</form>

<input value="JS打乱数组次序" onClick="rnd(aray)" type="button">

程序运行结果如下图所示,点击这里亲自运行看看