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
函数,很高兴知道,谢谢=)