Skip to main content
JMFreeman
Inspiring
January 28, 2020
Answered

Function with Multiple Returns

  • January 28, 2020
  • 2 replies
  • 935 views

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 has been closed for replies.
Correct answer Thom Parker

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.  

2 replies

Thom Parker
Community Expert
Thom ParkerCommunity ExpertCorrect answer
Community Expert
January 28, 2020

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
JMFreeman
JMFreemanAuthor
Inspiring
January 28, 2020

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

Thom Parker
Community Expert
Community Expert
January 28, 2020

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. 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Bernd Alheit
Community Expert
Community Expert
January 28, 2020

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