How to run a randomly selected function in JavaScript?

javascript, jquery

Solution

One option is to use `window` object:

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

Problem

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> ``` and then: ``` <button onclick="randomchords()" >Get some random chords</button> ``` Am I on the right track?

Original source