First, do not use extra space
Ideas: random exchange
Array.prototype.shuffle = function () {
var array = this;
for (var i = array.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = array[randomIndex];
array[randomIndex] = array[i];
array[i] = itemAtIndex;
}
return array;
};
Second, the use of additional space
Idea: Every time a random number drawn from the array into the new array, and then delete the number from the original array
Array.prototype.shuffle = function () {
var array = this
var len = array.length
var newArray = []
while (len > 0) {
var randomIndex = Math.floor(Math.random() * len)
var itemAtIndex = array[randomIndex]
newArray.push(itemAtIndex)
array.splice(randomIndex, 1)
len--
}
return newArray
}