如何在JavaScript中运行随机选择的函数? [英] How to run a randomly selected function in JavaScript?
本文介绍了如何在JavaScript中运行随机选择的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试运行一个随机函数,但还没有弄明白:
I'm trying to run a random function but haven't quite figured it out:
<script>
function randomFrom(array) {return array[Math.floor(Math.random() * array.length)];}
function randomchords(){randomFrom(['poop()', 'poop2()', 'poop3()']);}
function poop() { $(function() {ionian_c_vi() }); }
function poop2() { $(function() {ionian_c_iii() }), $(function() {ionian_c_iv() }); }
function poop3() { $(function() {ionian_c_vi() }), $(function() {ionian_c_i() }), $(function() {ionian_c_ii() }); }
</script>
然后:
<button onclick="randomchords()" >Get some random chords</button>
我是否走在正确的轨道上?
Am I on the right track?
推荐答案
一种选择是使用窗口
对象:
function randomchords() {
var func = randomFrom(['poop', 'poop2', 'poop3']);
window[func]();
}
注意你应该从数组中的函数名中删除括号。
Pay attention that you should remove parentheses from function names in the array.
另一种选择是从上面的变体中删除引号并直接调用函数:
Another option is to remove quotes from the variant above and call functions directly:
function randomchords() {
var func = randomFrom([poop, poop2, poop3]);
(func)();
}
这篇关于如何在JavaScript中运行随机选择的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文