_.sample(list, [n])
从list中产生一个随机样本。传参n后返回n个随机元素,各元素不重复。
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));
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后,返回的是数组。
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]
var list = [1, 2, 3, 4, 5];
var sample;
_(3).times(function(){
sample = _.sample(list, 5);
console.log(sample);
});
console.log(_.sample([])); //=> undefined
console.log(_.sample(1)); //=> undefined
console.log(_.sample(null)); //=> undefined
console.log(_.sample(undefined)); //=> undefined
console.log(_.sample(NaN)); //=> undefined
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"]