In JavaScript, shuffling an array refers to rearranging its elements in a random order.
The modern version of the Fisher-Yates shuffle algorithm can be implemented as:
/** * 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; } return a; }
The ES6 version of the algorithm can be written as:
/** * 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; }
To make the function more versatile, it can be implemented as a prototype method for array:
Object.defineProperty(Array.prototype, 'shuffle', { value: function() { for (let i = this.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [this[i], this[j]] = [this[j], this[i]]; } return this; } });
The following example demonstrates how to use the shuffle function:
const myArray = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; shuffle(myArray); console.log(myArray); // Logs a shuffled array
The above is the detailed content of How Can I Shuffle an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!