简体   繁体   中英

JavaScript random order functions

I have the following problem:

I want to call my functions func1() , func2() & func3() in a random order. But i want to be sure that every function is called!

If it's possible it also would be nice that no functions are used; just a random order of code sequences. Like this:

function xy(){

   //Call this sequence first second or third
   doSomething1

   //Call this sequence first second or third
   doSomething2

   //Call this sequence first second or third
   doSomething3

   //!! But call each sequence !!

}


Thanks in advance ;)

You could put all function names as strings into an Array, then sort this array randomly and call the functions:

var funcArr = new Array("func1", "func2", "func3");
shuffle(funcArr); //You would need a shuffle function for that. Can be easily found on the internet.

for (var i = 0; i < funcArr.length; i++)
    window[funcArr[i]]();

EDIT: If you don't want functions but lines of code to be sorted randomly, then that's not going to work. JavaScript does not have a goto command (at least not without an external API), so you can't jump between code lines. You can only mix functions, as shown above.

There is many ways to do that, one of the most easy way is like this:

Array.prototype.shuffle = function () {
  this.sort(function() { return 0.5 - Math.random() });
}

[func1, func2, func3].shuffle().forEach(function(func, index, array){
  func();
});

You can use something like the Fisher-Yates shuffle for shuffling the functions and then call them via Array.prototype.forEach() :

 var a = function () { alert('a'); }, b = function () { alert('b'); }, c = function () { alert('c'); }, array = [a, b, c]; array = array.map(function (a, i, o) { var j = (Math.random() * (o.length - i) | 0) + i, t = o[j]; o[j] = a; return t; }); array.forEach(function (a) { a(); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM