_.sample(collection)

87

_.sample(collection)
_.sample获取数组中的一个随机元素

参数

collection (Array|Object): 需要获取随机元素的集合

返回值

(*): 返回随机元素

例子

_.sample([1, 2, 3, 4]);
// => 2

源代码:

/**
 * Gets a random element from `array`.
 *
 * @since 2.0.0
 * @category Array
 * @param {Array} array The array to sample.
 * @returns {*} Returns the random element.
 * @example
 *
 * sample([1, 2, 3, 4])
 * // => 2
 */
//获取数组中的一个随机元素
function sample(array) {
  const length = array == null ? 0 : array.length//数组长度
  return length ? array[Math.floor(Math.random() * length)] : undefined
  //产生随机数[0, length]获取对应元素返回
}

export default sample

 

posted @ 2018-11-11 13:47  hahazexia  阅读(449)  评论(0)    收藏  举报