Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a randomly selected function in 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>

and then:

<button onclick="randomchords()" >Get some random chords</button>

Am I on the right track?

like image 284
jthomasbailey Avatar asked May 21 '12 22:05

jthomasbailey


People also ask

How do you call a random function?

rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.

Is there a random function in JavaScript?

In JavaScript, random() is a function that is used to return a pseudo-random number or random number within a range. Because the random() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

How do you randomly select a variable in JavaScript?

To create a random number in Javascript, the math. random() function is used. JavaScript math. random() generates a random decimal value between 0 and 1.


2 Answers

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)();
}
like image 147
VisioN Avatar answered Oct 17 '22 18:10

VisioN


Functions are like values. You could say:

var myArray = [
    function(){
        ionian_c_vi();
    },
    function(){
        ionian_c_iii();
        ionian_c_iv()
    },
    function(){
        ionian_c_vi();
        ionian_c_i();
    }
];
function randomchords(){ 
     randomFrom(myArray).call();
}

For more info, look at http://www.yuiblog.com/blog/2010/02/24/video-crockonjs-3/ and/or read at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call

Bookwise, read Javascript: The Good Parts (120 pages)

Helps learn JS outside jQuery :)

like image 6
Aadaam Avatar answered Oct 17 '22 19:10

Aadaam