-1

I am working in AngularJS and trying to send data to my backend.

I noticed that when the variable in my service has this structure test = [Object, Object] it gets passed into a List<String> in my ASP.NET backend, but i have trouble passing test = Array(2) into my backend.

I see the formats when i am debugging and set a breakpoint on the variable.

Is there a difference between the two? Thanks

alphapilgrim
  • 3,761
  • 8
  • 29
  • 58
inhaler
  • 415
  • 2
  • 7
  • 20
  • What are you trying to do here? just initialize an Array with the length == 2? – sethro Jun 06 '17 at 21:35
  • Obviously the one contains two functions while the other contains nothing. – Bergi Jun 06 '17 at 21:37
  • Please show your real code and present your [actual problem](https://meta.stackexchange.com/q/66377). – Bergi Jun 06 '17 at 21:38
  • It would be hard to post the code as the arrays are created after a few service calls and some changes. @Dai comment explains what the problem is. – inhaler Jun 06 '17 at 21:46

1 Answers1

3

The first case:

var x = { foo: "bar", qux: 123 };
var y = { baz: "123", yeen: { arr: [1,2,3] };

var test = [ x, y ]; // [Object,Object]

For the second case, refer to MDN's documentation for Array():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

new Array(arrayLength)

If the only argument passed to the Array constructor is an integer between 0 and 2^32 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number

So your second case code presumably is:

var test = Array(2);

...this actually evaluates to [undefined,undefined]), however .NET (thus ASP.NET) does not have a concept of "undefined" (compared to null), so this value is not serializable to JSON (as JSON does not allow undefined values) - so this explains why it's failing.

If an "empty" array element is meaningful in your application you should use explicit null values instead - ideally using an array-literal like so:

var ret = [ null, null ];

Or if the number of elements is variable:

var ret = Array( 123 ); // This creates a 123-sized array, where every element is undefined. This cannot be serialized to JSON
ret.fill( null );       // This explicitly sets every element to a null value. The array can now be serialized to JSON.
Dai
  • 141,631
  • 28
  • 261
  • 374