Results 1 to 3 of 3

Thread: Variable in Object Oriented String

  1. #1
    Join Date
    May 2005

    Variable in Object Oriented String

    The goal of the program is to show a number of questions in various text fields when the user hits a button, and to show the answers to the questions when the user hits a separate button. I am using self created objects to hold the values for both questions and answers.

    The following is the Object:
    var question_0 = new Object();
    question_0.question1 = new String("What are the processor speeds for a Classic Pentium?");
    question_0.answer1 = new String("60MHz-200MHz");
    question_0.question2 = new String("What are the system bus speeds for a Classic Pentium?");
    question_0.answer2 = new String("60MHz, 66MHz");
    question_0.question3 = new String("How much cache does the Classic Pentium have?");
    question_0.answer3 = new String("16K L1 Cache");
    I use a random number times the max number of items to choose which question to use. This is the following:
    function createRandom() {
    random = Math.round(Math.random() * max_questions);
    When the user hits the button, it calls this function:
    function randomQuestion() {
    var showQuestion = "question_"+random;
    document.formQuestion.first_question.value = showQuestion.question1;
    document.formQuestion.second_question.value = showQuestion.question2;
    document.formQuestion.third_question.value = showQuestion.question3;
    first_question, second_question, and third_question are text boxes within the formQuestion form.

    The issue is this. When I put "question_0.question1" it shows the value successfully. When I try to use showQuestion or the equivalent in the text box line, it gives me an undefined value.

    I'm not sure what the issue is, and would appreciate any possible help. Thank you.


  2. #2
    Join Date
    Jun 2007
    showQuestion is a string and does not refer to one of your objects.
    To get the reference you want, you can use this syntax:
    var showQuestion = window[ "question_" + random ];

  3. #3
    Join Date
    Apr 2008
    You might find it easier to store all the questions in an array, rather than individual variables..



    rather than...


    Also be careful with your Math.round(), you will find it will most likely need to be Math.floor(). Thinking of the following scenario...
    You have 5 questions, so max_questions is set to 5.
    Math.random() hits 5.5, you round it, and get 6.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center

Recent Articles