Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 什么';stringify(参数)是怎么回事?_Javascript_Json_Arguments - Fatal编程技术网

Javascript 什么';stringify(参数)是怎么回事?

Javascript 什么';stringify(参数)是怎么回事?,javascript,json,arguments,Javascript,Json,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

为什么参数不能字符串化为数组

有没有一种不那么冗长的方法使参数像数组一样字符串化

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]


这不仅仅是为了在控制台中观看。其思想是,在ajax请求中使用字符串,然后另一方对其进行解析,希望得到一个数组,但得到的是其他内容。

之所以出现这种情况,是因为参数不是数组,而是数组。您的解决方法是将其转换为实际阵列。JSON.stringify的行为与这里设计的一样,但它不是很直观。

因为它是一个类似数组的对象,而不是数组。您可以执行
[].slice.call
而不是
Array.prototype.slice.call
是的,这样会更短,而且消息更少。谢谢。您还可以做什么:
arguments.toJSON=[].slice;log(JSON.stringify(参数)):-)@Bergi Nice!,我不知道你能给一个对象分配一个
toJSON
函数,很高兴知道,谢谢=)