js

Array shuffle

하나에하나 2016. 1. 28. 19:42

의외로 js엔 셔플이 없어서 찾아보니


Array.prototype.shuffle = function() {
    var input = this;
     
    for (var i = input.length-1; i >=0; i--) {
     
        var randomIndex = Math.floor(Math.random()*(i+1));
        var itemAtIndex = input[randomIndex];
         
        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
    return input;
}


확장해서 사용하면 된단다.


사용예: Array.shuffle()


출처 : http://www.kirupa.com/html5/shuffling_array_js.htm