法一:
var arr =[1,2,3,4];var t;for(var i = 0;i < arr.length; i++){ var rand = parseInt(Math.random()*arr.length); t = arr[rand]; arr[rand] =arr[i]; arr[i] = t; } console.log(arr);
法二:
1 2 3 4 5 6 7 8 9 | var arr =[1,2,3,4]; var brr = []; var num = arr.length; for ( var i = 0; i < num; i++){ var temp = parseInt(Math.random()*(num-i)); brr.push(arr[temp]); arr.splice(temp,1); } console.log(brr); |
法三:---best way.
1 2 3 4 5 | function randomsort(a, b) { return Math.random()>.5 ? -1 : 1; //通过随机产生0到1的数,然后判断是否大于0.5从而影响排序,产生随机性的效果。 } var arr = [1, 2, 3, 4, 5]; arr.sort(randomsort); |