sobota, 11 lutego 2012

Array shuffle

Implementacja funkcji mieszającej elementy tablicy w języku JavaScript.
Array.prototype.shuffle = function(){
  return this.sort(function(){
    return Math.random() - 0.5;
  });
};
Przykład użycia:
[1, 2, 3].shuffle();
Poniżej inna implementacja bez użycia prototypów.
var shuffle = function(arr){
  return arr.sort(function(){
    return Math.random() - 0.5;
  });
};

Brak komentarzy:

Prześlij komentarz