Copy link to clipboard
Copied
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
…
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.
Copy link to clipboard
Copied
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.
Copy link to clipboard
Copied
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);
}
for(var i = 0; i < myArray.length; i++){
alert('i++\n' + 'index: ' + i + ' value: ' + myArray);
}
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 😉
Copy link to clipboard
Copied
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
Copy link to clipboard
Copied
Thank you Hans and Kasyan for your replies and example code. I appreciate it! 🙂