How to randomize subset of array in Javascript?

后端 未结 4 1537
死守一世寂寞
死守一世寂寞 2021-01-25 18:22

What is the best way to randomize part of the array in Javascript

For example, if I have 100 items in the array, what is the fast and efficient way of randomizing set of

4条回答
  •  深忆病人
    2021-01-25 18:59

    The following shuffles the specified chunk of an array in place, as randomly as the environment's random number generator will allow:

    function shuffleSubarray(arr, start, length) {
        var i = length, temp, index;
        while (i--) {
            index = start + Math.floor(i * Math.random());
            temp = arr[index];
            arr[index] = arr[start + i];
            arr[start + i] = temp;
        }
        return arr;
    }
    
    var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    alert( shuffleSubarray(a, 2, 5) );
    

提交回复
热议问题