JSON.stringify(参数)发生了什么?

Pau*_*aul 5 javascript json arguments

为什么没有参数stringify到数组?

是否有一种不那么冗长的方式使参数stringify像一个数组?

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]
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/w7SQF/

这不仅仅是在控制台中观看.我们的想法是,字符串在ajax请求中使用,然后另一方解析它,并且想要一个数组,但却获得了其他东西.

小智 4

发生这种情况是因为参数不是数组,而是类似数组的对象。您的解决方法是将其转换为实际的数组。JSON.stringify 的行为符合此处的设计,但不是很直观。