JavaScript - 隨機獲取數組元素

1.應用場景

隨機獲取數組元素.

2.學習/操作

1.隨機獲取數組一個元素

var items = ['1','2','4','5','6','7','8','9','10'];
var item = items[Math.floor(Math.random()*items.length)];

2.隨機獲取幾個元素

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);
}


var items = ['1','2','4','5','6','7','8','9','10'];
console.log( getRandomArrayElements(items, 4) );

截圖:

 

 

後續補充

...

3.問題/補充

TBD

4.參考

https://www.cnblogs.com/doseoer/p/5728955.html  //js隨機從數組中取出幾個元素

後續補充

...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章