Paul
Paul

Reputation: 27443

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

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.

Upvotes: 6

Views: 3419

Answers (2)

Hernán Eche
Hernán Eche

Reputation: 6898

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

Upvotes: 0

seelmobile
seelmobile

Reputation: 126

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.

Upvotes: 4

Related Questions