js从题库中随机抽取指定数的题目

2024年07月29日 建站教程

var items = [
	{name:'小白',age:'23'},
	{name:'小白2',age:'23'},
	{name:'小白3',age:'23'},
	{name:'小白4',age:'23'},
	{name:'小白5',age:'23'},
	{name:'小白6',age:'23'},
	{name:'小白7',age:'23'},
	{name:'小白8',age:'23'},
	{name:'小白9',age:'23'},
	{name:'小白10',age:'23'}
];
//抽取随机数组
function getRandomArrayElements(arr, count) {
	var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
	while (i-- > min) {
		index = Math.floor((i + 1) * Math.random());
		temp = shuffled[index];
		shuffled[index] = shuffled[i];
		shuffled[i] = temp;
	}
	return shuffled.slice(min);
}
//打印
console.log( getRandomArrayElements(items, 4) );

本文链接:http://so.lmcjl.com/news/9422/

展开阅读全文