_.shuffle(collection)


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM