“JavaScript Random Array Element Nein Wiederholung” Code-Antworten

JavaScript Random Array Element Nein Wiederholung

function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length < 1) { copy = array.slice(0); }
    var index = Math.floor(Math.random() * copy.length);
    var item = copy[index];
    copy.splice(index, 1);
    return item;
  };
}

var chooser = randomNoRepeats(['Foo', 'Bar', 'Gah']);
chooser(); // => "Bar"
chooser(); // => "Foo"
chooser(); // => "Gah"
chooser(); // => "Foo" -- only repeats once all items are exhausted.
Jealous Jellyfish

JavaScript nicht wieder aufzunehmen Randomize Array

var nums = [1,2,3,4,5,6,7,8,9,10],//all numbers to be randomized
    ranNums = [],
    i = nums.length,
    j = 0;

while (i--) {
    j = Math.floor(Math.random() * (i+1));
    ranNums.push(nums[j]);
    nums.splice(j,1);
}
ranNums.next().value; //To use afterwards (for each time that the numbers are used)
OverSin

JavaScript Random Array Element Nein Wiederholung

var a = ["Roger", "Russell", "Clyde", "Egbert", "Clare", "Bobbie", "Simon", "Elizabeth", "Ted", "Caroline"];

var chooseName = function () {
    var unique = true;
    num = Math.floor(Math.random() * a.length - 5);
    name = a.splice(num,1);
    a.push(name);
}


window.addEventListener("keypress", function (e) {
    var keycode = e.keyCode;
    if (keycode == 13) {
        chooseName();
    }
}, false);
Jealous Jellyfish

Ähnliche Antworten wie “JavaScript Random Array Element Nein Wiederholung”

Fragen ähnlich wie “JavaScript Random Array Element Nein Wiederholung”

Weitere verwandte Antworten zu “JavaScript Random Array Element Nein Wiederholung” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen