for(i in array)

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

    #1

    for(i in array)

    Hi,

    For objects (non-arrays) I can use for(i in object) to loop through all its
    members. For arrays, this does not always seem to work, and I am forced to
    use for(i=0; i<array.length; i++) instead. Is there a way to make an array
    accessible using the for-in loop? During my experiments I found that if the
    array is a member of an object, but not the first one, the for-in will
    work... seems a strange behaviour to me, so I'd be grateful if someone could
    shed some light on this for me.

    Greetings,
    Thomas


  • Richard Cornford

    #2
    Re: for(i in array)

    Thomas Mlynarczyk wrote:[color=blue]
    > For objects (non-arrays) I can use for(i in object)
    > to loop through all its members.[/color]

    To loop through the _enumerable_ members.
    [color=blue]
    > For arrays, this does not always seem to work,[/color]

    I have seen no evidence of any ECMAScript implementations exhibiting
    incorrect (unspecified) behaviour with for-in loos (except Netscape 4,
    with respect to the Type of the property name value, only).
    [color=blue]
    > and I am forced to use
    > for(i=0; i<array.length; i++) instead.[/color]

    If the members of an Array object that have property names that
    sufficiently resemble 32 bit unsigned integers are the subject of
    interest (as is almost always the case) then a loop incrementing (or
    decrementing) a number and limited by the Array's - length - property is
    the correct/reliable approach.
    [color=blue]
    > Is there a way to make an array
    > accessible using the for-in loop?[/color]

    Arrays are objects and will exhibit the (ECMA 262) specified behaviour
    when used as the subject of a for-in loop.
    [color=blue]
    > During my experiments I found that if the array
    > is a member of an object, but not the first one, the for-in
    > will work... seems a strange behaviour to me, so I'd be
    > grateful if someone could shed some light on this for me.[/color]

    In the above you have declared unshown code as 'working' or 'not
    working', without stating the criteria for either. As, in a strictly
    technical sense, all computer code 'works' (the computer mindlessly
    follows the instructions provided regardless of the outcome), it is
    almost always necessarily to explain what intended/expected behaviour
    corresponds with your definition of 'works', and provide that
    demonstrates how you are achieving 'not working'.

    Richard.


    Comment

    • Thomas Mlynarczyk

      #3
      Re: for(i in array)

      Also sprach Richard Cornford:
      [color=blue]
      > Thomas Mlynarczyk wrote:[color=green]
      >> For objects (non-arrays) I can use for(i in object)
      >> to loop through all its members.[/color]
      >
      > To loop through the _enumerable_ members.[/color]

      Is there a website which explains this issue in more detail?
      [color=blue]
      > Arrays are objects and will exhibit the (ECMA 262) specified behaviour
      > when used as the subject of a for-in loop.[/color]

      Does this mean if I access an array using for-in it should work and if it
      doesn't there must be a bug in my script?
      [color=blue]
      > In the above you have declared unshown code as 'working' or 'not
      > working', without stating the criteria for either. As, in a strictly
      > technical sense, all computer code 'works' (the computer mindlessly
      > follows the instructions provided regardless of the outcome), it is
      > almost always necessarily to explain what intended/expected behaviour
      > corresponds with your definition of 'works', and provide that
      > demonstrates how you are achieving 'not working'.[/color]

      Strangely, I was not able to reproduce the behaviour in a minimal test case,
      so it seems that it is indeed a bug in my original script, even though I
      cannot see how it could be possible. My script has a function which takes an
      object as argument (usually created "on the fly" in the function call
      statement). It loops through it using for-in and displays the member names
      and their values. If a value is an object (or array), it recursively loops
      through its members to display them as well.



      Comment

      • Michael Winter

        #4
        Re: for(i in array)

        Thomas Mlynarczyk wrote:
        [color=blue]
        > Also sprach Richard Cornford:[/color]

        [snip]
        [color=blue][color=green]
        >> To loop through the _enumerable_ members.[/color]
        >
        > Is there a website which explains this issue in more detail?[/color]

        Not to my knowledge, though it is explained in the ECMAScript
        specification[1] (8.6.1). In any case, it's quite simple.

        All object properties have a set of attributes associated with them.
        These attributes are ReadOnly, DontEnum, DontDelete, and Internal. The
        specification gives standardised properties preset attributes -
        namely, most (perhaps all? I'm not going to look right now :D) methods
        and properties are marked DontEnum. Host objects may, or may not,
        define attributes for their properties. It's up to the implementor.

        Whilst you can access DontEnum properties, you can only do so
        directly. The for..in statement will not discover these properties.

        Unfortunately, user code cannot manipulate property attributes. Any
        user-created properties will have no attributes set.
        [color=blue][color=green]
        >> Arrays are objects and will exhibit the (ECMA 262) specified behaviour
        >> when used as the subject of a for-in loop.[/color]
        >
        > Does this mean if I access an array using for-in it should work and if it
        > doesn't there must be a bug in my script?[/color]

        There might be a bug in the ECMAScript implementation, but yes, it
        could be your code.

        Hope that helps,
        Mike

        [1]
        <URL:http://www.ecma-international.o rg/publications/files/ecma-st/ECMA-262.pdf>

        --
        Michael Winter
        Replace ".invalid" with ".uk" to reply by e-mail.

        Comment

        • Richard Cornford

          #5
          Re: for(i in array)

          Thomas Mlynarczyk wrote:[color=blue]
          > Also sprach Richard Cornford:[color=green]
          >> Thomas Mlynarczyk wrote:[color=darkred]
          >>> For objects (non-arrays) I can use for(i in object)
          >>> to loop through all its members.[/color]
          >>
          >> To loop through the _enumerable_ members.[/color]
          >
          > Is there a website which explains this issue in more detail?[/color]

          What issue? ECMA 262 says that the for-in statement should behave in a
          particular way and language implementations behave in that way.
          [color=blue][color=green]
          >> Arrays are objects and will exhibit the (ECMA 262) specified
          >> behaviour when used as the subject of a for-in loop.[/color]
          >
          > Does this mean if I access an array using for-in it should
          > work and if it doesn't there must be a bug in my script?[/color]

          How are you defining 'work' and 'doesn't (work)'?

          <snip>[color=blue][color=green]
          >> ..., it is almost always necessarily to explain
          >> what intended/expected behaviour corresponds
          >> with your definition of 'works', and provide that[/color][/color]
          ^^^^^^^^^^^^
          That should have read "provide code that ...".
          [color=blue][color=green]
          >> demonstrates how you are achieving 'not working'.[/color]
          >
          > Strangely, I was not able to reproduce the behaviour
          > in a minimal test case, so it seems that it is indeed
          > a bug in my original script, even though I cannot
          > see how it could be possible. ...[/color]
          <snip>

          And nobody else can _see_ it either.

          However, when you cannot reproduce a problem by isolating the suspected
          cause you have eliminated that possibility as the cause of the problem
          and know that it is time to look elsewhere.

          Richard.


          Comment

          • Thomas Mlynarczyk

            #6
            Re: for(i in array)

            Also sprach Michael Winter:
            [color=blue]
            > All object properties have a set of attributes associated with them.
            > These attributes are ReadOnly, DontEnum, DontDelete, and Internal. The
            > specification gives standardised properties preset attributes -
            > namely, most (perhaps all? I'm not going to look right now :D) methods
            > and properties are marked DontEnum. Host objects may, or may not,
            > define attributes for their properties. It's up to the implementor.
            > Whilst you can access DontEnum properties, you can only do so
            > directly. The for..in statement will not discover these properties.
            > Unfortunately, user code cannot manipulate property attributes. Any
            > user-created properties will have no attributes set.[/color]

            Thanks for the explanation. I had noticed, that, when looping recursively
            through a DOM object (like document), the for-in loop seems to do several
            rounds, but no data is retrieved. Moreover, in some browsers I get an error
            like "Could not access...". Is this likely to be a bug in my script?


            Comment

            • Grant Wagner

              #7
              Re: for(i in array)

              "Thomas Mlynarczyk" <blue_elephant5 5@hotmail.com> wrote in message
              news:d01cbl$qso $04$1@news.t-online.com...[color=blue]
              > Also sprach Michael Winter:
              >[color=green]
              >> All object properties have a set of attributes associated with them.
              >> These attributes are ReadOnly, DontEnum, DontDelete, and Internal.
              >> The
              >> specification gives standardised properties preset attributes -
              >> namely, most (perhaps all? I'm not going to look right now :D)
              >> methods
              >> and properties are marked DontEnum. Host objects may, or may not,
              >> define attributes for their properties. It's up to the implementor.
              >> Whilst you can access DontEnum properties, you can only do so
              >> directly. The for..in statement will not discover these properties.
              >> Unfortunately, user code cannot manipulate property attributes. Any
              >> user-created properties will have no attributes set.[/color]
              >
              > Thanks for the explanation. I had noticed, that, when looping
              > recursively
              > through a DOM object (like document), the for-in loop seems to do
              > several
              > rounds, but no data is retrieved. Moreover, in some browsers I get an
              > error
              > like "Could not access...". Is this likely to be a bug in my script?[/color]

              No, it is not a bug in your script. Some properties of some host objects
              in some browsers are not accessible.

              For example, the following works as expected in Internet Explorer:

              for (var prop in navigator)
              {
              document.write(
              prop + ' = ' + navigator[prop] +
              ' (type: ' + typeof navigator[prop] + ')<br>'
              );
              }

              However:

              for (var prop in navigator.plugi ns)
              {
              document.write(
              prop + ' = ' + navigator.plugi ns[prop] +
              ' (type: ' + typeof navigator.plugi ns[prop] + ')<br>'
              );
              }

              Produces an "Object doesn't support this property or method" error, even
              though navigator.plugi ns reports typeof "object" when enumerating the
              navigator object.

              As a result, it is not a good idea to recursively enumerate the
              enumerable properties of host objects (and their child objects), since
              you can not guarantee it will not produce an unrecoverable error.

              --
              Grant Wagner <gwagner@agrico reunited.com>
              comp.lang.javas cript FAQ - http://jibbering.com/faq


              Comment

              • Thomas Mlynarczyk

                #8
                Re: for(i in array)

                Also sprach Grant Wagner:
                [color=blue]
                > As a result, it is not a good idea to recursively enumerate the
                > enumerable properties of host objects (and their child objects), since
                > you can not guarantee it will not produce an unrecoverable error.[/color]

                So there are objects which don't like to be asked about their properties...
                And no way to find out before one tries accessing them? Or could I somehow
                use try-catch to skip such objects?


                Comment

                • Douglas Crockford

                  #9
                  Re: for(i in array)

                  >>As a result, it is not a good idea to recursively enumerate the[color=blue][color=green]
                  >>enumerable properties of host objects (and their child objects), since
                  >>you can not guarantee it will not produce an unrecoverable error.[/color][/color]
                  [color=blue]
                  > So there are objects which don't like to be asked about their properties...
                  > And no way to find out before one tries accessing them? Or could I somehow
                  > use try-catch to skip such objects?[/color]

                  You can try, but that will produce syntax errors at load time on old
                  browsers.

                  Comment

                  • Douglas Crockford

                    #10
                    Re: for(i in array)

                    >>> As a result, it is not a good idea to recursively enumerate the[color=blue][color=green][color=darkred]
                    >>> enumerable properties of host objects (and their child objects), since
                    >>> you can not guarantee it will not produce an unrecoverable error.[/color][/color]
                    >
                    >[color=green]
                    >> So there are objects which don't like to be asked about their
                    >> properties...
                    >> And no way to find out before one tries accessing them? Or could I
                    >> somehow
                    >> use try-catch to skip such objects?[/color]
                    >
                    >
                    > You can try, but that will produce syntax errors at load time on old
                    > browsers.[/color]

                    I have had some success with the isAlien function, but I haven't tested
                    it on all browsers.

                    function isAlien(a) {
                    return isObject(a) && typeof a.constructor != 'function';
                    }

                    Comment

                    • Thomas Mlynarczyk

                      #11
                      Re: for(i in array)

                      Also sprach Douglas Crockford:
                      [color=blue][color=green][color=darkred]
                      >>> use try-catch to skip such objects?[/color]
                      >> You can try, but that will produce syntax errors at load time on old
                      >> browsers.[/color][/color]

                      Well, it doesn't have to work on NN<6, OP<7, IE<5 etc..
                      [color=blue]
                      > I have had some success with the isAlien function, but I haven't
                      > tested it on all browsers.
                      >
                      > function isAlien(a) {
                      > return isObject(a) && typeof a.constructor != 'function';
                      > }[/color]

                      So if(isAlien(myOb ject)) {/* don't use for-in on it */}? That, however,
                      seems to exclude all host objects, so I couldn't loop through the document
                      object.


                      Comment

                      Working...