繁体   English   中英

JavaScript随机顺序函数

[英]JavaScript random order functions

我有以下问题:

我想以随机顺序调用函数func1()func2()func3() 但我想确保每个函数都被调用!

如果可能的话,不使用任何功能也很好。 只是代码序列的随机顺序。 像这样:

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 !!

}


提前致谢 ;)

您可以将所有函数名称作为字符串放入数组中,然后对该数组进行随机排序并调用函数:

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]]();

编辑:如果您不希望函数而是随机对代码行进行排序,那么这将行不通。 JavaScript没有goto命令(至少没有外部API),因此您不能在代码行之间跳转。 您只能混合功能,如上所示。

有很多方法可以做到这一点,最简单的方法之一就是这样:

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

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

您可以使用诸如Fisher-Yates混洗之类的函数对函数进行Array.prototype.forEach() ,然后通过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(); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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