0

This is a javascript code. I have a collection of 10 functions card11() to card25(). On-click in another HTML code, I want one of these functions to be called randomly. I applied the following logic, but it seems to be flawed. HELP, please!

 arr=[card11(), card12(), card13(), card14(), card15(), card21(), card22(), card23() , card24(), card25()];
    function myFunc(arr)
    {
      var d, c, b = arr.length;
      while (b)
      {
          c = Math.floor(Math.random() * b);
          d = arr[--b];
          arr[b] = arr[c];
          arr[c] = d;
      }
           return arr;
    }
3
  • 2
    I could be wrong, but those seem to be variations of the same function. Have you considered making a single more generic function with a parameter instead of the 10 you have now? Commented Jan 16, 2014 at 10:06
  • Umm I do not know how I can do that. The functions are pretty complex. Commented Jan 16, 2014 at 10:20
  • Perhaps you could post on CodeReview if you think the problem is interesting enough. Make sure the code is working first! Commented Jan 16, 2014 at 10:27

1 Answer 1

2

First, the array should contain references to the function instead of executing the function:

var arr=[card11, card12, card13, card14, card15, card21, card22, card23 , card24, card25];

Next, you can easily call a random function that array using this function:

function callRandom(arr){
    arr[Math.floor(Math.random() * arr.length)]();
}

Example Usage

function func1(){
    alert("func2");
}
function func2(){
    alert("func1");
}
function func3(){
    alert("func1");
}

var arr = [func1, func2, func3];


function callRandom(arr){
    arr[Math.floor(Math.random() * arr.length)]();
}

callRandom(arr);

JS Fiddle: http://jsfiddle.net/cqLLV/1/

Sign up to request clarification or add additional context in comments.

3 Comments

<td> <img src="card.jpg" id="a" onclick="myFunc(arr)"> </td> Would this be the right way to call it in HTML? I do not know what to pass as a parameter, since I am defining the array in the script file.
@user3193046 You should attach the event with addEventListener instead of inlining the handler.
No, I got it! I just declared the array locally inside the function and didnt pass any parameters. Its working fine now. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.