Loop de Loops
Repeating scripts, counting stuff, and automating processes with JavaScript loops

“JavaScript loops are very handy for repeating scripts, counting things, and automating processes. They can be executed easily from the JavaScript console in Acrobat Pro. The variable in a loop is incremented (or decremented) to determine how many iterations should be performed.”
In my last post I described a number of things that are zero-based in JavaScript:
Page numbers
Field widgets
The Nth field name
The Nth word on a page
Array items in general, and more specifically, annotations, templates, and OCGs (layers)
This makes it easy to loop through any of these by setting the initial variable to zero and continuing the loop as long as the number stays below the total number. For example, if you want to loop through all of the pages in a document the loop would look like this:
for(var i=0; i<this.numPages; i++)
{
//your code to do something for each page number
}
Or if you want to loop through all of the annotations in a document the loop would look like this:
var anot = this.getAnnots();
for(var i=0; i<anot.length; i++)
{
//your script to do something for each annotation
}
Loop Through All Words On A Page
for(var i=0; i<this.getPageNumWords(0); i++)
{
//your script to do something with each word on page 1
}
Loop Through All Pages - Loop Through All Words On Those Pages
A Loop Inside A Loop
for(var i=0; i<this.numPages; i++)
{
//Loop through the words on the page
for(var j=0; j<this.getPageNumWords(i); j++)
{
//your script to do something with each word on each page
}
}
Break - Stop The Loop When Condition Is Met
Search for the word Zoology:
for(var i=0; i<this.numPages; i++)
{
//Loop through the words on the page
for(var j=0; j<this.getPageNumWords(i); j++)
{
if(this.getPageNumWords(i)=="Zoology")
{app.alert("Found Zoology");break}
}
}
Continue - To The Next Iteration
It is common to loop through all of the field names in a document and then do something with the field objects that possess those names. I don’t know how it happens but sometimes the fields are gone, but the names remain. Calling a non-existent field object will throw an error and stop the script. This can be avoided by testing for a field’s non-existence and using the word "continue" to ignore the rest of the script in the loop and continue to the next iteration.
/*The following script loops through all the field names and tests the field objects with those names for the type of field. If the type of field is a text field, the alignment is set to left*/
for(var i = 0; i< this.numFields; i++)
{
var fName = this.getNthFieldName(i);
var f=this.getField(fName);
if(f==null) {continue}
/*if there's no field object for the field name, the script below this line is not executed, but the loop continues to the next iteration*/
if(f.type=="text")
{f.alignment="left"}
}