1. /**
    2. * Copies the values of `source` to `array`.
    3. *
    4. * @private
    5. * @param {Array} source The array to copy values from.
    6. * @param {Array} [array=[]] The array to copy values to.
    7. * @returns {Array} Returns `array`.
    8. */
    9. function copyArray(source, array) {
    10. let index = -1
    11. const length = source.length
    12. array || (array = new Array(length))
    13. while (++index < length) {
    14. array[index] = source[index]
    15. }
    16. return array
    17. }
    18. /**
    19. * Creates an array of shuffled values, using a version of the
    20. * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
    21. *
    22. * @since 0.1.0
    23. * @category Array
    24. * @param {Array} array The array to shuffle.
    25. * @returns {Array} Returns the new shuffled array.
    26. * @example
    27. *
    28. * shuffle([1, 2, 3, 4])
    29. * // => [4, 1, 3, 2]
    30. */
    31. function shuffle(array) {
    32. const length = array == null ? 0 : array.length
    33. if (!length) {
    34. return []
    35. }
    36. let index = -1
    37. const lastIndex = length - 1
    38. const result = copyArray(array)
    39. while (++index < length) {
    40. // 求一个 lastIndex 到 index 之间的随机值
    41. const rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
    42. // 交换两个值
    43. const value = result[rand]
    44. result[rand] = result[index]
    45. result[index] = value
    46. }
    47. return result
    48. }
    1. function shuffle(array) {
    2. var m = array.length, t, i;
    3. // While there remain elements to shuffle…
    4. while (m) {
    5. // Pick a remaining element…
    6. i = Math.floor(Math.random() * m--);
    7. // And swap it with the current element.
    8. t = array[m];
    9. array[m] = array[i];
    10. array[i] = t;
    11. }
    12. return array;
    13. }