如何从预定义的集合中选择随机函数?

时间:2013-09-23 15:25:00

标签: javascript jquery

如果我定义了这些功能:

function playZoomout() {
// do things
}
function playZoomin() {
// do things
}
function playPanright() {
// do things
}
function playPanleft() {
// do things
}

我每四秒钟运行一次:

var timer = setInterval(playZoomout,4000);

如何将“playZoomout”替换为从上面定义的中随机选择的函数?我正在寻找一个jQuery或简单的JavaScript解决方案。

3 个答案:

答案 0 :(得分:3)

创建一个函数引用数组,然后从数组中随机获取一个元素并调用它。

var fns = [playZoomout, playZoomin, playPanright, playPanleft]
setInterval(function () {
    fns[Math.floor(Math.random() * fns.length)]();
}, 1000)

演示:Fiddle

答案 1 :(得分:0)

使用数字键索引将每个函数名添加到数组中。然后,在下部和上部索引之间随机生成一个数字,并使用控制结构重复该过程。

答案 2 :(得分:0)

这样的事情应该有用(见http://jsfiddle.net/w6sdc/):

/* A few functions */
var a = function() {
    alert("A");
}

var b = function() {
    alert("B");
}

var c = function() {
    alert("C");
}

/* Add the functions to an array */
var funcs = [a, b, c];

/* Select a random array index */
var i = Math.floor(Math.random() * 2) + 0;

/* Call the function at that index */
funcs[i]();

setInterval开始包装索引选择和函数调用应该是直截了当的。