调用没有重复的随机函数

调用没有重复的随机函数

本文介绍了调用没有重复的随机函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a random photo365 challenge list generator using javascript. I have a list of 365 different function which come up with a different assignment name/page link (this probably isn't the best way to do it, but it works)It works as it's supposed to, it does call 365 functions and puts them in a list...

但我想做的是防止重复.(请注意,下面的代码没有列出所有的 365 函数)

But what I'd like to do is prevent repeats. (Please note, the code below doesn't have all the 365 functions listed)

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

I have searched on stack overflow, and I have come across a variety of methods of preventing repeats. But any time I try to add the new code it, I can't get it to work.

我真的不擅长 JavaScript,因此非常感谢您提供的任何指导......

I'm really not that skilled in javascript, so any guidance you could provide would be extremely appreciated...

诺尔

//新建待办事项

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

推荐答案

我会这样做:

//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)();
}

这篇关于调用没有重复的随机函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:25