Obtenir l'élément aléatoire à partir du tableau JavaScript [dupliquer]

cette question a déjà une réponse ici:

  • obtention d'une valeur aléatoire à partir d'un tableau JavaScript 22 réponses
var items = Array(523,3452,334,31,...5346);

Comment puis-je obtenir l'article aléatoire de items ?

622
demandé sur Kyle Kelley 2011-05-06 21:47:45

13 réponses

var item = items[Math.floor(Math.random()*items.length)];
1386
répondu Kelly 2011-05-06 17:50:19

Si vous avez vraiment doit utiliser jQuery pour résoudre ce problème:

(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // chosen by fair dice roll
        }
    };
})(jQuery);

var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);

ce plugin retournera un élément aléatoire si on lui donne un tableau, ou une valeur de [0 .. n) étant donné un nombre, ou n'importe quoi d'autre, une valeur aléatoire garantie!

pour le plaisir supplémentaire, le retour du tableau est généré en appelant la fonction de façon récursive basée sur la longueur du tableau:)

démo de travail à http://jsfiddle.net/2eyQX /

86
répondu Alnitak 2016-03-04 15:54:02

utiliser le soulignement (ou loDash :)):

var randomArray = [
   '#cc0000','#00cc00', '#0000cc'
];

// use _.sample
var randomElement = _.sample(randomArray);

// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];

ou pour mélanger un tableau entier:

// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];
76
répondu chim 2014-12-17 10:31:18
var random = items[Math.floor(Math.random()*items.length)]
32
répondu Rocket Hazmat 2011-05-06 17:50:39

1. solution: définir le prototype de réseau

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

qui va travailler sur inline tableaux

[2,3,5].random()

et bien sûr des tableaux prédéfinis

list = [2,3,5]
list.random()

2. solution: définir la fonction personnalisée qui accepte la liste et renvoie l'élément

get_random = function (list) {
  return list[Math.floor((Math.random()*list.length))];
} 

get_random([2,3,5])
25
répondu dux 2015-11-28 06:43:43

Voici encore une autre façon:

function rand(items) {
    return items[~~(items.length * Math.random())];
}
22
répondu K-Gun 2017-11-08 17:35:19

jQuery est JavaScript! C'est juste un cadre JavaScript. Donc, pour trouver un élément aléatoire, il suffit d'utiliser le Vieux JavaScript, par exemple,

var randomItem = items[Math.floor(Math.random()*items.length)]
13
répondu planetjones 2014-08-19 21:05:39
var rndval=items[Math.floor(Math.random()*items.length)];
11
répondu Blindy 2011-05-06 17:50:25
var items = Array(523,3452,334,31,...5346);

function rand(min, max) {
  var offset = min;
  var range = (max - min) + 1;

  var randomNumber = Math.floor( Math.random() * range) + offset;
  return randomNumber;
}


randomNumber = rand(0, items.length - 1);

randomItem = items[randomNumber];

crédit:

Fonction Javascript: Générateur De Nombres Aléatoires

8
répondu neebz 2016-01-22 22:02:31
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})

// 2. Get first item
var item = items[0]

plus court:

var item = items.sort(function() {return 0.5 - Math.random()})[0];
7
répondu Ivan 2015-11-28 07:01:51

si vous utilisez node.js, vous pouvez utiliser unique-au hasard-tableau . Il choisit simplement quelque chose au hasard dans un tableau.

4
répondu Aayan L 2015-04-18 00:04:57

une autre façon serait d'ajouter une méthode au prototype du réseau:

 Array.prototype.random = function (length) {
       return this[Math.floor((Math.random()*length))];
 }

 var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
 var chosen_team = teams.random(teams.length)
 alert(chosen_team)
1
répondu James Daly 2014-08-19 21:06:00
const ArrayRandomModule = {
  // get random item from array
  random: function (array) {
    return array[Math.random() * array.length | 0];
  },

  // [mutate]: extract from given array a random item
  pick: function (array, i) {
    return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
  },

  // [mutate]: shuffle the given array
  shuffle: function (array) {
    for (var i = array.length; i > 0; --i)
      array.push(array.splice(Math.random() * i | 0, 1)[0]);
    return array;
  }
}
1
répondu Nicolas 2018-08-29 15:47:47