调用随机函数而不重复

时间:2014-01-17 19:32:34

标签: javascript random

我正在使用javascript创建一个随机的photo365挑战列表生成器。我有一个365个不同功能的列表,它提供了一个不同的任务名称/页面链接(这可能不是最好的方法,但它的工作原理) 它按预期工作,它会调用365个函数并将它们放在一个列表中......

但我想做的是防止重复。 (请注意,下面的代码没有列出所有365个功能)

我搜索了堆栈溢出,我遇到了各种防止重复的方法。但是每当我尝试添加新代码时,我都无法让它工作。

我真的不擅长javascript,所以你能提供的任何指导都会非常感激......

诺尔

//创建新的待办事项

function randomFrom(array) {return array[Math.floor(Math.random() * array.length)];}
 function randomCreate() {
    var func = randomFrom([createNew365ToDo, 
                           createNew365ToDoBulb, 
                           createNew365ToDo2, 
                           createNew365ToDoShallow, 
                           createNew365ToDoWide, 
                           createNew365ToDoLenses, 
                           createNew365ToDoMacro, 
                           createNew365ToDoAToZ]);
    (func)();
}

function createNew365ToDoList()
{
    deleteAll365Rows();
    for (var p = 0; p < 365; p++) { 
    { 
         randomCreate();
    }
}}

1 个答案:

答案 0 :(得分:0)

我会做这样的事情:

//are arrays passed by reference? I don't remember, so let's just make it available to everything to demonstrate

var fnArray = [createNew365ToDo, createNew365ToDoBulb, createNew365ToDo2, createNew365ToDoShallow, createNew365ToDoWide, createNew365ToDoLenses, createNew365ToDoMacro,createNew365ToDoAToZ];

function randomFunction() {
    //get a random index from the list
    var index = Math.floor(Math.random() * fnArray.length);
    //save that function to fn, and REMOVE it from the list
    var fn = fnArray.splice(index, 1);
    //return that function - now, when randomFunction() gets called again, you won't ever 
    //return the same function since it's no longer in the list
    return fn;
}

function callRandomFunction() {
  var func = randomFunction();
  (func)();
}