89
_.shuffle(collection)
_.shuffle創建一個打亂順序的數組,使用Fisher–Yates shuffle洗牌算法
參數
collection (Array|Object): 需要打亂順序的集合
返回值
(Array): 返回打亂順序的數組
例子
_.shuffle([1, 2, 3, 4]); // => [4, 1, 3, 2]
源代碼:
import copyArray from './.internal/copyArray.js' /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @since 0.1.0 * @category Array * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * shuffle([1, 2, 3, 4]) * // => [4, 1, 3, 2] */ //創建一個打亂順序的數組,使用Fisher–Yates shuffle洗牌算法 function shuffle(array) { const length = array == null ? 0 : array.length//數組長度 if (!length) {//如果數組長度為0,返回空數組 return [] } let index = -1//循環索引 const lastIndex = length - 1//數組的最后一個元素的索引 const result = copyArray(array)//復制一份原始數組作為結果數組 while (++index < length) {//循環數組長度次 const rand = index + Math.floor(Math.random() * (lastIndex - index + 1)) //生成隨機索引,每一次的范圍都比上一次少一個 const value = result[rand]//結果數組中對應隨機索引的值先存下來,然后和result[index]互換位置 result[rand] = result[index] result[index] = value } return result//返回打亂順序后的新數組 } export default shuffle
copyArray
/** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ //復制source數組的值到array里 function copyArray(source, array) { let index = -1//循環索引 const length = source.length//source數組長度 array || (array = new Array(length))//如果沒有array參數,就新建一個和source長度一樣的數組作為array while (++index < length) {//循環source,復制source的元素到array里 array[index] = source[index] } return array//返回array } export default copyArray