JSON.stringify(arguments) 发生了什么?

6

为什么arguments不能直接转换成数组?

有没有更简单的方法让arguments像数组一样转换成字符串?

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/

这不仅仅是在控制台中查看。想法是将字符串用于ajax请求,然后另一端解析它,并希望得到一个数组,但实际上却得到了其他结果。


6
因为arguments是类似于数组的对象而不是真正的数组,所以你可以使用[].slice.call代替Array.prototype.slice.call - Moritz Roessler
是的,这样会更简短,也不会有太多的消息传递。谢谢。 - Paul
4
你还可以这样做:arguments.toJSON = [].slice; console.log(JSON.stringify(arguments)); :-) - Bergi
@Bergi 很好!我不知道你可以将 toJSON 函数分配给一个对象,很好知道,谢谢 =) - Moritz Roessler
2个回答

4
这是因为arguments不是一个数组,而是一个类似数组的对象。你需要将其转换为实际的数组来解决问题。JSON.stringify在这里表现正常,但并不是很直观。

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接