Subba Reddy Alamur
Subba Reddy Alamur

Reputation: 55

ServiceNow - list is updated only with last value

I have a problem with the Javascript code in ServiceNow platform. Below is the code.

var results = [];
var gr = new GlideRecord('incident');
//gr.orderByDesc('sys_created_on');
gr.setLimit(5);
gr.query();
while(gr.next()) {
  gs.print(gr.number);
  results.push(gr.number);
  //gs.print(results);
}
gs.print(results);

and I get output as

*** Script: INC0000060
*** Script: INC0009002
*** Script: INC0000009
*** Script: INC0000010
*** Script: INC0000011
*** Script: INC0000011,INC0000011,INC0000011,INC0000011,INC0000011

As you can see gs.print(gr.number) is giving correct output where when I push that into a list 'results' its not getting update but only updating with the last value.

Has anyone faced similar kind of issue? Please help me understand where the problem is.

Upvotes: 0

Views: 1126

Answers (2)

giles3
giles3

Reputation: 487

When you write results.push(gr.number) you are pushing a GlideElement onto your list. A GlideElement is an object, so you are actually pushing the address of the object onto your list. When you call gr.next() the GlideElements are populated with new values, but they are the same GlideElements. It would be extremely inefficient for ServiceNow to allocate new memory for all the elements in a record every time you read a new record. When you get to the end of your loop you have 5 references to the same GlideElement, and it contains the last value read.

When you write results.push(gr.number.toString()) you are pushing a string value onto your list (not an object), and that it why it works.

Upvotes: 1

Subba Reddy Alamur
Subba Reddy Alamur

Reputation: 55

converting gr.number to string and pushing to array will work.

results.push(gr.number.toString());

I would like to understand why didn't it work with just gr.number.

Upvotes: 0

Related Questions