Reputation: 27443
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]
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
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