Skip to main content
JMFreeman
Inspiring
Jan 28, 2020 4:13 PM UTC
Answered

Function with Multiple Returns

I have this little script for getting objects on a given page:

function getFieldOn(name, p){//finds (the first) field on page p with 'name' in its name
    var fields;
    for(var i = 0; i < this.numFields; i++){
        var f = this.getField(this.getNthFieldName(i));
        if ((f.name.indexOf(name) > -1) && (f.page == p)) return f;
    }
}

I'd like to modify this so it can return a single object if that's all it finds, and return an array of objects if there are multiple objects sharing the same name or partial name. Can I have two types of return values like that? How can I modify this code?

This topic is closed to new replies. Start a new post to keep the conversation going.
Thom Parker
Thom ParkerCorrect answer
Community Expert
Jan 28, 2020 6:11 PM UTC

Add an array object to collect all the fields. 

 

    var fieldsd, aRslts = [];
    for(var i = 0; i < this.numFields; i++){
        var f = this.getField(this.getNthFieldName(i));
        if ((f.name.indexOf(name) > -1) && (f.page == p)) aRslt.push(f);
    }
    return (aRslts.length==1)?aRslts[0]:aRslts;

 

Note that this code returns an empty array if there are no fields found.  

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often

7 replies

Thom Parker
Community Expert
Thom ParkerCommunity ExpertCorrect answer
Community Expert
Jan 28, 2020 6:11 PM UTC

Add an array object to collect all the fields. 

 

    var fieldsd, aRslts = [];
    for(var i = 0; i < this.numFields; i++){
        var f = this.getField(this.getNthFieldName(i));
        if ((f.name.indexOf(name) > -1) && (f.page == p)) aRslt.push(f);
    }
    return (aRslts.length==1)?aRslts[0]:aRslts;

 

Note that this code returns an empty array if there are no fields found.  

Translate
Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
JMFreeman
JMFreemanAuthor
Inspiring
Jan 28, 2020 6:19 PM UTC

Sweet, thanks! Why is the logic check needed in the last line of your code?

Translate
Thom Parker
Community Expert
Community Expert
Jan 28, 2020 6:35 PM UTC

The conditional on the return tests for a single result. If there is only one, then it returns just that one. Otherwise the entire array is returned. 

Translate
Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Bernd Alheit
Community Expert
Community Expert
Jan 28, 2020 4:46 PM UTC

You can return a single object or an array of objects.

Translate