Array .indexOf() method not working

Mike McCall
Giga Guru

I realize this could be a general JavaScript question, but it seems like it should be working in the "real world" (and is failing within Service-Now). Basically, I'm using a business rule to look through an array of values from a custom status field I've added to [grc_remediation]:


     var grRemediations = new GlideRecord('grc_remediation');
...
     var aRemediationStatuses = new Array();
     while (grRemediations.next()) {
           aRemediationStatuses.push(grRemediations.u_status.toLowerCase());
     }
...
     gs.log('aRemediationStatuses: ' + aRemediationStatuses);
     // The statement above will return 'aRemediationStatuses: work in progress,open'.

     gs.log('aRemediationStatuses.indexOf("open"): ' + aRemediationStatuses.indexOf('open'));
     /*
           The statement above will return 'aRemediationStatuses.indexOf("open"): undefined'.
           Shouldn't it return 'aRemediationStatuses.indexOf("open"): 1'?
       */

I need to know where a value is showing up within an array (or if it's not in the array at all), but I just keep getting 'undefined' returned by .indexOf(), and I have verified that the array is properly populated. Any suggestions?
1 ACCEPTED SOLUTION

For anyone that runs across this post as I did today.   A colleague of mine just mentioned .indexOf() works in Helsinki for arrays.   I tried it between Geneva and Helsinki and indeed it does work!



var s='Detroit,London,Tokyo';


var s2 = s.split(',');


var a = s2.indexOf("London");


gs.print(a);



In Geneva I get "undefined"


In Helsinki I get "1"


View solution in original post

17 REPLIES 17

john_roberts
Mega Guru

Checkout ArrayUtil helper.


CapaJC
ServiceNow Employee
ServiceNow Employee

Could be that whatever version of Rhino/JavaScript is currently being used in ServiceNow to evaluate JavaScript on the server doesn't support indexOf for Arrays.

If that's the case, you can use the ArrayUtil Script Include which has an indexOf function in it. Use would be like this:



gs.log('aRemediationStatuses.indexOf("open"): ' + ArrayUtil.indexOf(aRemediationStatuses, "open");


Mike McCall
Giga Guru

Thanks, guys! Sure enough, using the ArrayUtil() script include worked:



...
var oArrayUtil = new ArrayUtil();
gs.log('ArrayUtil.indexOf(aRemediationStatuses, "open"): ' + oArrayUtil.indexOf(aRemediationStatuses, 'open'));


benn23
ServiceNow Employee
ServiceNow Employee

This should work also:
aRemediationStatuses.toString().indexOf('open')