Incorrect result on array using includes()

KB15
Giga Guru

I've used a similar script in the past which works but I'm not sure why I'm not getting the results this time around. I'm placing variable results into an array and attempting to evaluated the array with includes(). The result is never yes even though the array contains the correct value. I'm running this as a background script for testing purposes.

var array = [];

                                                             

var gr = new GlideRecord('sc_req_item');

gr.addQuery('request', 'd65ec5b7130dc3000b63b86f3244b076');

gr.query();

while (gr.next()) {

        array.push(gr.variables.request_type_hardware);

}

gs.print(array);

if (array.includes('replacement_upgrade')) {

gs.print('yes');

        }

}

This is the array result:

find_real_file.png

1 ACCEPTED SOLUTION

Community Alums
Not applicable

That is entirely possible, though I would assume it's system-wide, as SN Rhino engine only supports ECMAScript 2015. I could be way out to lunch here, though



I just did this test in a background script:



var arrayUtil = new ArrayUtil();


var aNew = ['apples', 'oranges', 'bananas'];



if (aNew.includes('apples')) {


gs.print("includes");


}


if (arrayUtil.contains(aNew, 'apples')) {


gs.print("Util");


}



Only 'Util' was printed to the output.



Cheers,



Tim


View solution in original post

10 REPLIES 10

Community Alums
Not applicable

I may be incorrect, but I don't think the Array 'includes()' method is available in ServiceNow JS engine at this time. It's an ECMAScript 2016 method:



Array.prototype.includes() - JavaScript | MDN



filter() and map() are available if that helps. You could also try using the 'ArrayUtil' library, it has a similar method called 'contains()':



https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=c_ArrayUtilAPI



Cheers,



Tim


Hmm, I'm currently running on our instance in a script include and seems to be working correctly. Are you saying that it's just not functional in a background script?


Community Alums
Not applicable

That is entirely possible, though I would assume it's system-wide, as SN Rhino engine only supports ECMAScript 2015. I could be way out to lunch here, though



I just did this test in a background script:



var arrayUtil = new ArrayUtil();


var aNew = ['apples', 'oranges', 'bananas'];



if (aNew.includes('apples')) {


gs.print("includes");


}


if (arrayUtil.contains(aNew, 'apples')) {


gs.print("Util");


}



Only 'Util' was printed to the output.



Cheers,



Tim


OK. I'll try this. I asked this question because I had weird inconsistent results with ArrayUtil prior.