Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
Paul Avatar asked Jul 09 '13 11:07

Paul


1 Answers

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.

like image 134
seelmobile Avatar answered Nov 18 '22 01:11

seelmobile