What's going on with JSON.stringify(arguments)?
Asked Answered
D

2

6

Why doesn't arguments stringify to an array ?

Is there a less verbose way to make arguments stringify like an array?

function wtf(){
  console.log(JSON.stringify(arguments));
  // the ugly workaround
  console.log(JSON.stringify(Array.prototype.slice.call(arguments)));
}

wtf(1,2,3,4);
-->
{"0":1,"1":2,"2":3,"3":4}
[1,2,3,4]


wtf.apply(null, [1,2,3,4]);
-->
{"0":1,"1":2,"2":3,"3":4}
[1,2,3,4]

http://jsfiddle.net/w7SQF/

This isn't just to watch in the console. The idea is that the string gets used in an ajax request, and then the other side parses it, and wants an array, but gets something else instead.

Dynamometry answered 9/7, 2013 at 11:22 Comment(4)
because arguments is an Array like Object, not an Array. you could do [].slice.call instead of Array.prototype.slice.callLouis
Yes, that would be shorter and have less MSG. Thanks.Dynamometry
What you could also do: arguments.toJSON = [].slice; console.log(JSON.stringify(arguments)); :-)Leeannaleeanne
@Leeannaleeanne Nice!, I dind't knew you can assign a toJSON function to an Object, good to know, thanks =)Louis
A
4

That's happening because arguments is not an array, but an array-like object. Your workaround is converting it to an actual array. JSON.stringify is behaving as designed here, but it's not very intuitive.

Argueta answered 9/7, 2013 at 11:30 Comment(0)
P
0

JSON.stringify([...arguments]));

Pung answered 31/7, 2021 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.