【发布时间】:2013-07-06 23:39:00
【问题描述】:
为什么不将参数字符串化为数组?
有没有更简洁的方法让参数像数组一样字符串化?
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 请求中,然后对方解析它,并想要一个数组,但得到其他东西。
【问题讨论】:
-
因为 arguments 是一个类似于 Object 的数组,而不是数组。你可以做
[].slice.call而不是Array.prototype.slice.call -
是的,这样会更短,味精也更少。谢谢。
-
你还可以做什么:
arguments.toJSON = [].slice; console.log(JSON.stringify(arguments));:-) -
@Bergi 不错!,我不知道您可以将
toJSON函数分配给对象,很高兴知道,谢谢 =)
标签: javascript json arguments