【问题标题】:What's going on with JSON.stringify(arguments)?JSON.stringify(arguments) 是怎么回事?
【发布时间】: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]

http://jsfiddle.net/w7SQF/

这不仅仅是为了在控制台中观看。这个想法是字符串被用在 ajax 请求中,然后对方解析它,并想要一个数组,但得到其他东西。

【问题讨论】:

  • 因为 arguments 是一个类似于 Object 的数组,而不是数组。你可以做[].slice.call 而不是Array.prototype.slice.call
  • 是的,这样会更短,味精也更少。谢谢。
  • 你还可以做什么:arguments.toJSON = [].slice; console.log(JSON.stringify(arguments)); :-)
  • @Bergi 不错!,我不知道您可以将 toJSON 函数分配给对象,很高兴知道,谢谢 =)

标签: javascript json arguments


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    发生这种情况是因为参数不是一个数组,而是一个array-like object。您的解决方法是将其转换为实际数组。 JSON.stringify 的行为与此处设计的一样,但不是很直观。

    【讨论】:

      猜你喜欢
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      相关资源
      最近更新 更多