js 從數組中隨機抽取幾個元素

function getRandomArr(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);
}

調用

var items = ['1','2','4','5','6','7'];
console.log( getRandomArrayElements(items, 3) );
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章