这是怎么回事用JSON.stringify(参数)? [英] What's going on with JSON.stringify(arguments)?

查看:196
本文介绍了这是怎么回事用JSON.stringify(参数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么没有参数字符串化到一个数组?

Why doesn't arguments stringify to an array ?

有没有办法让参数字符串化就像一个数组?一个更简洁的方式

Is there a less verbose way to make arguments stringify like an array?

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请求使用,再在另一面解析它,想一个数组,但得到别的东西来代替。

This isn't just to watch in the console. The idea is that the string gets used in an ajax request, and then the other side parses it, and wants an array, but gets something else instead.

推荐答案

这是发生,因为论据是的不可以一个数组,而是一个<一href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments\"相对=nofollow>阵列状物体。您的变通办法将其转换为实际的数组。 JSON.stringify被表现为这里设计的,但它不是很直观。

That's happening because arguments is not an array, but an array-like object. Your workaround is converting it to an actual array. JSON.stringify is behaving as designed here, but it's not very intuitive.

这篇关于这是怎么回事用JSON.stringify(参数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆