JS从数组中随机取出几个数组元素的方法

原文链接:http://caibaojian.com/js-get-random-elements-from-array.html

js如何从一个数组中随机取出一个元素或者几个元素。

假如数组为·

var items = ['1','2','4','5','6','7','8','9','10'];

1.从数组items中随机取出一个元素

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) );
posted @ 2018-12-15 16:16  小猪冒泡  阅读(6756)  评论(0编辑  收藏  举报