-1

Start

So there is an array with numbers. Then it picks a random order from those numbers. those numbers correspond with functions and the functions are questions. Is there any way to do this. I am only ten and just started javascript so please help. Thanks in advance

HyperMonkey
  • 105
  • 1
  • 6

1 Answers1

1

Okay, so first let's think about your question a bit, then we'll get down to some code.

So first, it's awesome you thought of the array of numbers corresponding to functions! That kind of mapping, where numbers in the array correspond to the functions which represent questions is similar to a lot of what goes on under the hood of languages! However, in this case, we don't need it, since we can just make an array out of function pointers, which are a built-in way of doing just what you've described.

So let's make some example questions:

function Question1() { 
     window.alert("What is your favorite color?"); 
}

function Question2() { 
     window.alert("What is your favorite animal?"); 
}

so now we can call our questions, like this: Question1() and have that particular question output. Note that this doesn't deal with taking responses for now, just asking the question, to illustrate some array usage.

Now how can we call them from an array?

a = [Question1, Question2];
a[0](); /* This calls question 1 */

So now we can use rand to select a random question (with a helper function from Mozilla):

function getRandomInt(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min)) + min;
}

index = getRandomInt(0, a.length);
a[index](); /* Calls a random question */

And that's it! Also, I not another commentator used eval to solve this, which definitely works but generally isn't good practice due to it's vulnerabilities. If you go that direction, you might want to look into it.

Community
  • 1
  • 1
James Danylik
  • 371
  • 3
  • 6
  • Good introduction! Possible follow-up: Declare a `questions` array whose elements are the question texts and declare a generic `askRandomQuestion(questions)` function which picks a random element out of the supplied question texts array and asks that question via `alert`. – le_m May 16 '17 at 02:54
  • Also, I think OP was referring to a random permutation of natural numbers 1...n and asking all those questions in the order given by that permutation to avoid duplicate questions. You might want to talk about that a bit, too, if you have time :) – le_m May 16 '17 at 02:56
  • Thanks soo much it worked!!!:-) – HyperMonkey May 17 '17 at 01:51