How can I shuffle an array? [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

Possible Duplicate:
How to randomize a javascript array?

I want to shuffle an array of elements in JavaScript like these:

[0, 3, 3] -> [3, 0, 3] [9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6] [3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]

回答1:

Use :

/**  * Shuffles array in place.  * @param {Array} a items An array containing the items.  */ function shuffle(a) {     var j, x, i;     for (i = a.length - 1; i > 0; i--) {         j = Math.floor(Math.random() * (i + 1));         x = a[i];         a[i] = a[j];         a[j] = x;     } }

ES2015 (ES6) version

/**  * Shuffles array in place. ES6 version  * @param {Array} a items An array containing the items.  */ function shuffle(a) {     for (let i = a.length - 1; i > 0; i--) {         const j = Math.floor(Math.random() * (i + 1));         [a[i], a[j]] = [a[j], a[i]];     }     return a; }

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9']; shuffle(myArray);


回答2:

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {     let counter = array.length;      // While there are elements in the array     while (counter > 0) {         // Pick a random index         let index = Math.floor(Math.random() * counter);          // Decrease counter by 1         counter--;          // And swap the last element with it         let temp = array[counter];         array[counter] = array[index];         array[index] = temp;     }      return array; }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!