如何创建一个for循环来遍历不同的函数而不重复执行同一个函数

How to make a for loop that will go through functions without going through the same one twice

本文关键字:函数 同一个 复执 遍历 执行 循环 创建 何创建 for 一个      更新时间:2023-09-26

我有一些函数,如:

function functionOne() {
    /*
    code
    */
}
function functionTwo() {
    /*
    code
    */
}
function functionThree() {
    /*
    code
    */
}

我怎么能写代码调用每个函数,一次(即没有重复),在一个随机的顺序?

把你的函数放在一个数组中,随机化数组,然后遍历它:

var functions = [
function () {  alert("function 0");  },
function () {  alert("function 1");  },
function () {  alert("function 2");  },
function () {  alert("function 3");  },
function () {  alert("function 4");  }
    ];
functions.sort(function() { return 0.5 - Math.random() });
for (var i=0;i<5;i++) {
    console.log(i);
    functions[i]();
}

Here's fiddle

这个函数应该可以工作:

 function randCall(){
      var array = [1,2,3];
      while(array.length > 0){
          var rand = (Math.random*array.length)|0; //converts to an Integer value
          switch(array[rand]){
             case 1:
                  functionOne();
                  break;
             case 2:
                  functionTwo();
                  break;
             case 3:
                  functionThree();
                  break;
          }
          array.splice(rand, 1);
      }
 }

相关文章: