Associative array help needed.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ant

    Associative array help needed.

    Hi,

    I'm using an associative array to simulate a multidimensiona l array like
    this:

    myArray['00'] = "John";
    myArray['01'] = "35";
    myArray['02'] = "12345";
    myArray['03'] = "01/01/1975";

    myArray['10'] = "Sarah";
    myArray['11'] = "29";
    myArray['12'] = "56789";
    myArray['13'] = "12/12/19";

    I'm trying to work out how to loop through the entire array and I'm having
    some problems.

    for (var i = 0; i < arrayCount; i++)
    {
    for (var j = 0; j < attribCount; j++)
    {
    alert(myArray[i + j]);
    }
    }

    Now this doesn't work as it's adding the i and j together rather than
    joining them. And it doesn't work when I do 'i' and 'j' so I'm wondering, is
    it actually possible to loop through the array?

    Thanks for any help.


  • Bert

    #2
    Re: Associative array help needed.


    "Ant" <nospamf@nospam .com> schreef in bericht
    news:cvatc0$bgr $1@wisteria.csv .warwick.ac.uk. ..[color=blue]
    > Hi,
    >
    > I'm using an associative array to simulate a multidimensiona l array like
    > this:
    >
    > myArray['00'] = "John";
    > myArray['01'] = "35";
    > myArray['02'] = "12345";
    > myArray['03'] = "01/01/1975";
    >
    > myArray['10'] = "Sarah";
    > myArray['11'] = "29";
    > myArray['12'] = "56789";
    > myArray['13'] = "12/12/19";
    >
    > I'm trying to work out how to loop through the entire array and I'm having
    > some problems.
    >
    > for (var i = 0; i < arrayCount; i++)
    > {
    > for (var j = 0; j < attribCount; j++)
    > {
    > alert(myArray[i + j]);
    > }
    > }
    >
    > Now this doesn't work as it's adding the i and j together rather than
    > joining them. And it doesn't work when I do 'i' and 'j' so I'm wondering,
    > is it actually possible to loop through the array?
    >
    > Thanks for any help.
    >[/color]

    try:

    for (var i = 0; i < arrayCount; i++)
    {
    for (var j = 0; j < attribCount; j++)
    {
    alert(myArray[i*10 + j]);
    }
    }

    maybe for (var i = 0; i < arrayCount/10; i++)

    but I don't know what arraycount is....

    grt Bert


    Comment

    • Ant

      #3
      Re: Associative array help needed.

      "Bert" <b.bosch8@chell o.nl> wrote in message >[color=blue]
      > try:
      >
      > for (var i = 0; i < arrayCount; i++)
      > {
      > for (var j = 0; j < attribCount; j++)
      > {
      > alert(myArray[i*10 + j]);
      > }
      > }
      >
      > maybe for (var i = 0; i < arrayCount/10; i++)
      >
      > but I don't know what arraycount is....
      >
      > grt Bert[/color]

      That's really clever, I wish I'd thought of that.

      Ta


      Comment

      • Douglas Crockford

        #4
        Re: Associative array help needed.

        > I'm using an associative array to simulate a multidimensiona l array like[color=blue]
        > this:
        >
        > myArray['00'] = "John";
        > myArray['01'] = "35";
        > myArray['02'] = "12345";
        > myArray['03'] = "01/01/1975";
        >
        > myArray['10'] = "Sarah";
        > myArray['11'] = "29";
        > myArray['12'] = "56789";
        > myArray['13'] = "12/12/19";
        >
        > I'm trying to work out how to loop through the entire array and I'm having
        > some problems.[/color]

        There is a better representaion for this kind of data: an array of objects:

        myArray = [{
        name: "John",
        age: "35",
        number: "12345",
        date: "01/01/1975"},
        {
        name: "Sarah",
        age: "29",
        number: "56789",
        date: "12/12/19"}];


        Comment

        • RobG

          #5
          Re: Associative array help needed.

          Douglas Crockford wrote:
          [...][color=blue][color=green]
          >> I'm trying to work out how to loop through the entire array and I'm
          >> having some problems.[/color]
          >
          >
          > There is a better representaion for this kind of data: an array of objects:
          >
          > myArray = [{
          > name: "John",
          > age: "35",
          > number: "12345",
          > date: "01/01/1975"},
          > {
          > name: "Sarah",
          > age: "29",
          > number: "56789",
          > date: "12/12/19"}];
          >
          > http://www.JSON.org[/color]

          Yes Douglas - but the rest of the question was how to loop
          through the array. My guess is that the OP will attempt to call
          each element explicitly, but what about getting all of them
          without needing to know what they are called?

          So I had a go at looping through all the elements of all the
          objects, but I'm left with two questions (hopefully I've used
          do/while correctly!):

          1. Is there a way to avoid using eval?

          2. Is there an efficient way of putting the j decrement inside
          the while, but still get the zero-th element? I could have
          used:

          j = myArray.length;
          ...
          eval('myArray[j-1].' + anAttribute)
          ...
          while(--j)

          but (without testing) all those [j-1]'s seem inefficient.


          <script type="text/javascript">
          myArray = [{
          name: "John",
          age: "35",
          number: "12345",
          date: "01/01/1975"},
          {
          name: "Sarah",
          age: "29",
          number: "56789",
          date: "12/12/19"}];

          function sayArray() {
          var msg='',
          anAttribute,
          j;
          if (myArray) {
          j = myArray.length - 1;

          do {
          msg += '\nEntry: ' + j;
          for ( anAttribute in myArray[j]){
          msg += '\n ' + anAttribute + ': '
          + eval('myArray[j].' + anAttribute);
          }
          --j;
          } while(j >= 0);

          }
          alert(msg);
          }
          <button onclick="sayArr ay();">Say myArray</button>



          --
          Rob

          Comment

          • Randy Webb

            #6
            Re: Associative array help needed.

            RobG wrote:

            <--snip-->
            [color=blue]
            > 1. Is there a way to avoid using eval?[/color]

            Yes. Arrays (and Objects) are properties of the window object and
            accessible via the Array Notation.

            <--snip-->
            [color=blue]
            > msg += '\n ' + anAttribute + ': '
            > + eval('myArray[j].' + anAttribute);[/color]

            msg += '\n + anAttribute + ': '
            + window['myArray[j].' + anAttribute];

            --
            Randy
            comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly

            Comment

            • RobG

              #7
              Re: Associative array help needed.

              Randy Webb wrote:[color=blue]
              > RobG wrote:
              >
              > <--snip-->
              >[color=green]
              >> 1. Is there a way to avoid using eval?[/color]
              >
              >
              > Yes. Arrays (and Objects) are properties of the window object and
              > accessible via the Array Notation.
              >
              > <--snip-->
              >[color=green]
              >> msg += '\n ' + anAttribute + ': '
              >> + eval('myArray[j].' + anAttribute);[/color]
              >
              >
              > msg += '\n + anAttribute + ': '
              > + window['myArray[j].' + anAttribute];
              >[/color]

              Thanks Randy, I saw your answer to the cycling through functions
              post so I tried using the window object. I used every
              combination of square brackets & quotes I could think of
              (including your suggestion) but in both IE and Firefox it comes
              out as:

              Entry: 1
              name: undefined
              age: undefined
              ...


              --
              Rob

              Comment

              • Douglas Crockford

                #8
                Re: Associative array help needed.

                RobG wrote:[color=blue]
                > Douglas Crockford wrote:
                > [...]
                >[color=green][color=darkred]
                >>> I'm trying to work out how to loop through the entire array and I'm
                >>> having some problems.[/color]
                >>
                >>
                >>
                >> There is a better representaion for this kind of data: an array of
                >> objects:
                >>
                >> myArray = [{
                >> name: "John",
                >> age: "35",
                >> number: "12345",
                >> date: "01/01/1975"},
                >> {
                >> name: "Sarah",
                >> age: "29",
                >> number: "56789",
                >> date: "12/12/19"}];
                >>
                >> http://www.JSON.org[/color]
                >
                >
                > Yes Douglas - but the rest of the question was how to loop
                > through the array. My guess is that the OP will attempt to call
                > each element explicitly, but what about getting all of them
                > without needing to know what they are called?
                >
                > So I had a go at looping through all the elements of all the
                > objects, but I'm left with two questions (hopefully I've used
                > do/while correctly!):
                >
                > 1. Is there a way to avoid using eval?
                >
                > 2. Is there an efficient way of putting the j decrement inside
                > the while, but still get the zero-th element? I could have
                > used:
                >
                > j = myArray.length;
                > ...
                > eval('myArray[j-1].' + anAttribute)
                > ...
                > while(--j)
                >
                > but (without testing) all those [j-1]'s seem inefficient.
                >
                >
                > <script type="text/javascript">
                > myArray = [{
                > name: "John",
                > age: "35",
                > number: "12345",
                > date: "01/01/1975"},
                > {
                > name: "Sarah",
                > age: "29",
                > number: "56789",
                > date: "12/12/19"}];
                >
                > function sayArray() {
                > var msg='',
                > anAttribute,
                > j;
                > if (myArray) {
                > j = myArray.length - 1;
                >
                > do {
                > msg += '\nEntry: ' + j;
                > for ( anAttribute in myArray[j]){
                > msg += '\n ' + anAttribute + ': '
                > + eval('myArray[j].' + anAttribute);
                > }
                > --j;
                > } while(j >= 0);
                >
                > }
                > alert(msg);
                > }
                > <button onclick="sayArr ay();">Say myArray</button>[/color]

                That use of eval is totally and completely wrongheaded. Do it right:

                var i, k, o;
                var msg = '';
                for (i = 0; i < myArray.length; i += 1) {
                msg += 'Record: ' + i + '\n';
                o = myArray[i];
                for (k in o) {
                msg += ' ' + k + ': ' + o[k] '\n';
                }
                }

                If you ever find yourself using eval, you can be certain that you are
                doing it wrong.

                Who taught you to program like that? Where did you learn to use eval so
                badly? The guilty must be punished.


                Comment

                • RobG

                  #9
                  Re: Associative array help needed.

                  Douglas Crockford wrote:[color=blue]
                  > RobG wrote:
                  >[/color]
                  [...][color=blue][color=green]
                  >> So I had a go at looping through all the elements of all the
                  >> objects, but I'm left with two questions (hopefully I've used
                  >> do/while correctly!):
                  >>
                  >> 1. Is there a way to avoid using eval?
                  >>
                  >> 2. Is there an efficient way of putting the j decrement inside
                  >> the while, but still get the zero-th element? I could have
                  >> used:[/color][/color]
                  [...][color=blue]
                  >
                  > That use of eval is totally and completely wrongheaded. Do it right:
                  >
                  > var i, k, o;
                  > var msg = '';
                  > for (i = 0; i < myArray.length; i += 1) {
                  > msg += 'Record: ' + i + '\n';
                  > o = myArray[i];
                  > for (k in o) {
                  > msg += ' ' + k + ': ' + o[k] '\n';
                  > }
                  > }
                  >
                  > If you ever find yourself using eval, you can be certain that you are
                  > doing it wrong.
                  >
                  > Who taught you to program like that? Where did you learn to use eval so
                  > badly? The guilty must be punished.
                  >
                  > http://www.crockford.com/javascript/survey.html[/color]

                  I apologise most sincerely - the fervent dislike of eval by the
                  regulars of this new group is, well, bleedin' obvious, hence my
                  question.

                  Fortunately, there seems to be more tolerance of:

                  ... i < myArray.length; ... // slow when i is large?


                  ... i += 1) { // is i++ out of favour too?


                  ... + o[k] '\n'; // Ooops... + o[k] + '\n' works.


                  To err is human... :-)

                  --
                  Rob

                  Comment

                  • Dr John Stockton

                    #10
                    Re: Associative array help needed.

                    JRS: In article <cvatc0$bgr$1@w isteria.csv.war wick.ac.uk>, dated Sun,
                    20 Feb 2005 20:53:13, seen in news:comp.lang. javascript, Ant
                    <nospamf@nospam .com> posted :
                    [color=blue]
                    >myArray['00'] = "John";
                    >myArray['01'] = "35";
                    >myArray['02'] = "12345";
                    >myArray['03'] = "01/01/1975";
                    >
                    >myArray['10'] = "Sarah";
                    >myArray['11'] = "29";
                    >myArray['12'] = "56789";
                    >myArray['13'] = "12/12/19";[/color]

                    That's likely to be 1912/2012 December 19. Format YYYY/MM/DD should be
                    safe. Never use a date format that can be taken or mistaken for
                    MM/DD/YY[YY].

                    [color=blue]
                    >I'm trying to work out how to loop through the entire array and I'm having
                    >some problems.
                    >
                    >for (var i = 0; i < arrayCount; i++)
                    >{
                    > for (var j = 0; j < attribCount; j++)
                    > {
                    > alert(myArray[i + j]);
                    > }
                    >}
                    >
                    >Now this doesn't work as it's adding the i and j together rather than
                    >joining them.[/color]

                    i + '' + j // should join them

                    Operator + will concatenate if both arguments are strings, or if one is
                    string and the other is number; if both are number it will add. Other
                    types will be preconverted to number or to string.

                    Note too the other comments. See below.

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                    <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                    <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                    <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                    Comment

                    • RobB

                      #11
                      Re: Associative array help needed.


                      Randy Webb wrote:[color=blue]
                      > RobG wrote:
                      >
                      > <--snip-->
                      >[color=green]
                      > > 1. Is there a way to avoid using eval?[/color]
                      >
                      > Yes. Arrays (and Objects) are properties of the window object and
                      > accessible via the Array Notation.
                      >[/color]

                      (snip)

                      Only if they're stored as 'global' variables. Nothing native about
                      this.



                      Comment

                      Working...