js随机码之乱序数组

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 
11 <body>
12 
13 </body>
14 <script>
15     var times = 100000;
16     var res = {};
17 
18     for (var i = 0; i < times; i++) {
19         var arr = shuffle([1, 2, 3]);
20 
21         var key = JSON.stringify(arr);
22         res[key] ? res[key]++ : res[key] = 1;
23     }
24 
25     // 为了方便展示,转换成百分比
26     for (var key in res) {
27         res[key] = res[key] / times * 100 + '%'
28     }
29 
30     //ES5 
31     function shuffle(a) {
32         var j, x, i;
33         for (i = a.length; i; i--) {
34             j = Math.floor(Math.random() * i);
35             x = a[i - 1];
36             a[i - 1] = a[j];
37             a[j] = x;
38         }
39         return a;
40     }
41 
42 
43     //ES6 
44     function shuffle(a) {
45         for (let i = a.length; i; i--) {
46             let j = Math.floor(Math.random() * i);
47             [a[i - 1], a[j]] = [a[j], a[i - 1]];
48         }
49         return a;
50     }
51 
52     console.log(res)
53 </script>
54 
55 
56 </html>

 

posted @ 2017-10-30 16:11  Sunsin  阅读(824)  评论(0编辑  收藏  举报