Javascript different behavior server/client execution with arrays used as objects

#1

This code returns different results when executed server side or client side:

EmrTool.c3typ
testArrayReturn: function(value: string): json js server

EmrTool.js
function testArrayReturn(value) {
var a = [];
for (var i = 0; i < 10; i++) a.push(value + i);
a.name = “I’m an array”;
return a;
}

Note EmrTool is just a custom C3 type.

server side:

EmrTool.testArrayReturn(“a”)
(10) [“a0”, “a1”, “a2”, “a3”, “a4”, “a5”, “a6”, “a7”, “a8”, “a9”]

client side:

testArrayReturn(“a”)
(10) [“a0”, “a1”, “a2”, “a3”, “a4”, “a5”, “a6”, “a7”, “a8”, “a9”, name: “I’m an array”]

OK, I know that’s not good practice. Not a C3Type for the returned value and using Array as Object.

But that’s not cool because it makes my unit test failing. For example:
expect(EmrTool.testArrayReturn(“a”).name).toBe(“I’m an array”)
will be false.

Note that if the code EmrTool.testArrayReturn(“a”) is called internally, I mean server side, there are no problem, the full array-object is well returned.
It is only if the EmrTool.testArrayReturn(“a”) is called from client that gets incorrect results.
Probably because:

JSON.stringify(testArrayReturn(“a”))
"[“a0”,“a1”,“a2”,“a3”,“a4”,“a5”,“a6”,“a7”,“a8”,“a9”]"

see https://stackoverflow.com/questions/16196338/json-stringify-doesnt-work-with-normal-javascript-array

0 Likes