Looping through an array

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

    Looping through an array

    Take a look at this code:

    var arr = new Array();
    arr["id1"] = 1; // element 0
    arr["id5"] = 2; // element 1
    arr["id47"] = 3; // element 2

    Is it possible to loop through this array without knowing
    the string-id's? Just start out at element 0, and go on
    to 1 and 2 and print out the values?


    --
    Jarle Kaste
    jkaLOckEDste@on line.no ['Unlock' my address]


  • Lasse Reichstein Nielsen

    #2
    Re: Looping through an array

    "Jarle Kaste" <jkaLOckEDste@o nline.no> writes:
    [color=blue]
    > Take a look at this code:
    >
    > var arr = new Array();
    > arr["id1"] = 1; // element 0
    > arr["id5"] = 2; // element 1
    > arr["id47"] = 3; // element 2
    >
    > Is it possible to loop through this array without knowing
    > the string-id's? Just start out at element 0, and go on
    > to 1 and 2 and print out the values?[/color]

    First of all, there is no need to use an array when you don't use
    integer indices. You might as well use an object, i.e.
    var arr = new Object();

    To iterate through the properties of any object, you can use the
    for(...in...) construct:
    for (var i in arr) {
    ... arr[i] ...
    }

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • kaeli

      #3
      Re: Looping through an array

      In article <8SyRa.13810$Hb .236051@news4.e .nsc.no>,
      jkaLOckEDste@on line.no enlightened us with...[color=blue]
      > Take a look at this code:
      >
      > var arr = new Array();
      > arr["id1"] = 1; // element 0
      > arr["id5"] = 2; // element 1
      > arr["id47"] = 3; // element 2
      >
      > Is it possible to loop through this array without knowing
      > the string-id's? Just start out at element 0, and go on
      > to 1 and 2 and print out the values?
      >
      >
      >[/color]
      <body>
      hi
      <script>
      var arr = new Array();
      arr["id1"] = 1; // element 0
      arr["id5"] = 2; // element 1
      arr["id47"] = 3; // element 2
      for (v in arr)
      alert(arr[v]);

      </script>

      --
      -------------------------------------------------
      ~kaeli~
      There is no justification or rationalization
      for mutilation. Ban declawing as inhumane.


      -------------------------------------------------

      Comment

      Working...