数组元素随机换位

    <script type="text/javascript">
        let getRandomInt = function (min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min)
        }

        let shuffle = function(arr) {
           let _arr = arr.slice()
           for (let i = 0; i < _arr.length; i++) {
               let j = getRandomInt(0, i)
               let t = _arr[i]
               _arr[i] = _arr[j]
               _arr[j] = t
           }
           return _arr
        }

        let arr = [1, 2, 3, 4, 5, 6, 7]
        let random = shuffle(arr)
        console.log(random)
    </script>

 

posted @ 2017-10-28 14:12  Sorrow.X  阅读(465)  评论(0编辑  收藏  举报