SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2007
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript associative array - please correct my code

    Here's the code - it sits in the parent frameset of a sequence of pages but for convenience here I've just put the code and the readout in one block:
    var start=Array;
    start["yes"]="You started the investigation immediately."
    start["no"]="You didn't start the investigation immediately."
    start["check"]=false;

    var mtg=Array;
    mtg["yes"]="You set up a meeting promptly";
    mtg["no"]="You didn't set up a meeting promptly."
    mtg["check"]=true;

    var checklist=Array(start,mtg)

    document.write( checklist[0]["yes"] + "<br />" )
    What I'm trying to do:
    set up a number of checks on what the user does in a sequence of pages. If they do the right thing, the 'check' value is changed. At the end you report using the 'yes' and 'no' values.

    The problem:
    the master array 'checklist' doesn't hold the values of all the arrays, only the most recent one e.g. above it displays 'you set up a meeting properly' instead of 'you started the investigation immediately'. If I swap around the sequence in which start and mtg are declared, what is shown changes.

    I've obviously misunderstood how associative arrays work (I was following Jeremy Keith's DOM Scripting book pp24-5) - can anyone either correct my syntax or tell me a better way to approach this?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your two variables (start and mtg) are not arrays.

    Both are equal to the native Array constructor, and they each set yes,no and check properties on that object.

    The last one defined will replace any other value for the same property.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2007
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Aah! I forgot the () - how dumb!

    Thanks for pointing it out!

  4. #4
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Associative arrays are considered to be harmful. Use an object to achieve this instead.


Bookmarks

Posting Permissions

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