2.22 sample
2.22.1 语法:
_.sample(list, [n])
2.22.2 说明:
从list中产生一个随机样本。传参n后返回n个随机元素,各元素不重复。
2.22.3 代码示例:
示例一:从list中随机产生一个样本
var sample;
//数组
sample = _.sample([1, 2, 3, 4, 5]);
console.log(sample); //may be => Number 3
//对象
sample = _.sample({a:1, b:2, c:3, d:4, e: 5});
console.log(sample); //may be => Number 2
//字符串
sample = _.sample('12345');
console.log(sample); //may be => String 5
//arguments
(function(){
sample = _.sample(arguments);
console.log(sample); //may be => Number 1
}(1, 2, 3, 4, 5));
示例二:传递参数n
var sample;
//数组
sample = _.sample([1, 2, 3, 4, 5], 3);
console.log(sample); //may be => [4, 2, 3]
//对象
sample = _.sample({a:1, b:2, c:3, d:4, e: 5}, 3);
console.log(sample); //may be => [1, 2, 4]
//字符串
sample = _.sample('12345', 3);
console.log(sample); //may be => ["5", "1", "4"]
//arguments
(function(){
sample = _.sample(arguments, 3);
console.log(sample); //may be => [3, 2, 4]
}(1, 2, 3, 4, 5));
传递n后,返回的是数组。
2.22.3 传递参数n的变化
var list = [1, 2, 3, 4, 5];
var sample;
sample = _.sample(list, -1);
console.log(sample); //=> []
sample = _.sample(list, 0);
console.log(sample); //=> []
//传1返回的也是数组
sample = _.sample(list, 1);
console.log(sample); //may be => [1]
sample = _.sample(list, 3);
console.log(sample); //may be => [1, 2, 4]
sample = _.sample(list, 5);
console.log(sample); //may be => [5, 3, 1, 2, 4]
sample = _.sample(list, 10);
console.log(sample); //may be => [2, 4, 5, 1, 3]
- 传递了参数n返回的都是数组
- n <= 0 返回空数组
- n > 0 && n < list.length 返回的数组长度为n
- n >= list.length返回的数组长度为list.length
2.22.4 产生的一个样本内,各元素不会重复
var list = [1, 2, 3, 4, 5];
var sample;
_(3).times(function(){
sample = _.sample(list, 5);
console.log(sample);
});
2.22.5 非集合情况都返回undefined
console.log(_.sample([])); //=> undefined
console.log(_.sample(1)); //=> undefined
console.log(_.sample(null)); //=> undefined
console.log(_.sample(undefined)); //=> undefined
console.log(_.sample(NaN)); //=> undefined
2.22.6 简单的random,元素的值可能重复
var list = ['a', 'b', 'c', 'd'];
var sample = [];
for(var i = 0; i < list.length; i++) {
var n = Math.floor(Math.random() * list.length);
sample.push(list[n]);
}
console.log(sample); //maybe => ["c", "d", "c", "a"]