Copy link to clipboard
Copied
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?
1 Correct answer
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.
Copy link to clipboard
Copied
You can return a single object or an array of objects.
Copy link to clipboard
Copied
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.
Use the Acrobat JavaScript Reference early and often
Copy link to clipboard
Copied
Sweet, thanks! Why is the logic check needed in the last line of your code?
Copy link to clipboard
Copied
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.
Use the Acrobat JavaScript Reference early and often
Copy link to clipboard
Copied
I'm sure this is "best programming practice" at work, but I want to make sure I understand. Why do we need to check for this? What if the last line wre just
return aRslts;
and there was only one value in the array?
Copy link to clipboard
Copied
Then it would only return that one object, not an array.
Personally, I think it's better to know the type of object you're returning, so I would opt for returning an array always, either empty, or with one item, or with multiple items, but it's a matter of preference.
Copy link to clipboard
Copied
Personally I think you are better off just returning the "aRslts" array as you've just suggested. I presented the code as you asked for it. You specifically asked for two types of return objects.
Use the Acrobat JavaScript Reference early and often

