Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder Taro's Avatar
    Join Date
    Oct 2011
    Location
    Geraldton, Ontario
    Posts
    155
    Thanks
    1
    Thanked 1 Time in 1 Post

    What are some other ways to write JavaScript arrays?

    Hello,

    Are there other formats and configurations to write a JavaScript array? Note that there will be at least 100 pairs.

    Code:
    var thisArray = ["soda", "cake", "burger", "fries", "olive"]; 
    
    var thatArray = ["aws1", "xzv2", "poi3", "gdf4", "lkj5"];
    Each value must correspond to each other, and there can be no mismatch between values; the code will tend to be edited repeatedly after publishing.

    In advance, I appreciate any help to this matter.
    Last edited by Taro; 06-01-2012 at 01:11 AM.
    Element ID

    Webs Support Helper

    Your friendly neighborhood Taroman.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,550
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    Better:

    Code:
    function pair( a, b )
    {
        this.left = a;
        this.right = b;
    }
    
    var pairs = [
        pair("soda","awsl"), pair("cake","xzv2"), pair("burger","poi3"), ... 
       ];
    
    // to iterate through them:
    for ( var p = 0; p < pairs.length; ++p )
    {
         var first = pairs[p].left;
         var second = pairs[p].right;
         ... do something with first and second ...
    }
    // (the names used there are of course entirely up to you)
    Or, possibly even better:
    Code:
    // note the curly braces in place of square brackets!
    pairs = {
        "soda" : "awsl", 
        "cake" : "xzv2", 
        "burger" : "poi3",
         ...
        };
    
    // to iterate through them:
    for ( var first in pairs )
    {
        var second = pairs[first];
         ... do something with first and second ...
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    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
    •