4 Replies Latest reply on Sep 26, 2012 7:19 AM by thor2112

    Looping thru getFiles() array

    thor2112

      I've always heard it's best to use a sequential loop for arrays:

       

      var fileArray = folderPath.getFiles();

       

      for (var i = 0; i < fileArray.length; i++) {

          // Do stuff...

      }

       

      However, in the JavaScriptToolsGuide_CS5.pdf they use a "for - in" loop when looping through the getFiles() array:

       

      var pics = Folder(picFolder).getFiles();

      for (f in pics) {

          var file = pics[f];

          …

       

      Is there something different about the array created by getFiles() that makes it ok to do this?  getFiles() returns an array of File and Folder objects (or null if folder doesn't exist), so I'm assuming this is a normal array?

       

      Thanks.

        • 1. Re: Looping thru getFiles() array
          Kasyan Servetsky Level 5

          Stoyan Stefanov -- JavaScript Patterns, Page 17

          for-in loops should be used to iterate over nonarray objects. Looping with for-in is also called enumeration.

          Technically, you can also use for-in to loop over arrays (because in JavaScript arrays are objects), but it’s not recommended. It may lead to logical errors if the array object has already been augmented with custom functionality. Additionally, the order (the sequence) of listing the properties is not guaranteed in a for-in. So it’s preferable to use normal for loops with arrays and for-in loops for objects.

          • 2. Re: Looping thru getFiles() array
            -hans- Level 4

            Hi,

             

            in use:

             

            myArray =new Array();
            myArray[5] = 'five';
            myArray[3] = 'three';
            myArray[4] = 'four';
            
            
            for ( var i in myArray) {
            alert('for in ...\n' + 'index: ' + i +  '    value: ' + myArray[i]);
            }
            
            for(var i = 0; i < myArray.length; i++){
                alert('i++\n' + 'index: ' + i + '     value: ' + myArray[i]);
                }
            

             

            So, if you just want to iterate over all readable items of a array, regardless of their index: for(i in a) should also be ok.

             

            Hope it's the truth ;-)

            • 3. Re: Looping thru getFiles() array
              Trevorׅ Adobe Community Professional

              Hi Hans,

               

              Nice demonstration,

              Interesting to note that the order of the "in" loop is the order of the variable declarations (at least in this case)

               

              Trevor

              • 4. Re: Looping thru getFiles() array
                thor2112 Level 1

                Thank you Hans and Kasyan for your replies and example code.  I appreciate it!  :-)