Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON.stringify 和 toString 有什么区别? #31

Open
fwon opened this issue Mar 1, 2017 · 0 comments
Open

JSON.stringify 和 toString 有什么区别? #31

fwon opened this issue Mar 1, 2017 · 0 comments

Comments

@fwon
Copy link
Owner

fwon commented Mar 1, 2017

  1. 字符串,数字,布尔值的JSON.stringify(..)规则和ToString基本相同。
  2. 如果传递给JSON.stringify(..)的对象中定义了toJSON()方法,那么该方法会在字符串化前调用,以便将对象转换为安全的JSON值。

null 和 undefined 值没有toString方法。直接调用会报错,在不知道要转换的值是不是null或undefined的情况下,可以使用转型函数String()。这个函数能够将任何类型的值转换为字符串。String()函数遵循下列转换规则:

  1. 如果值有toString()方法,则调用该方法并返回相应结果;
  2. 如果值时null, 则返回"null";
  3. 如果值时undefined,则返回"undefined"。

在调用 数值的 toString()方法时,可以传递一个参数:输出数值的基数,默认采用的是10进制

var num = 10;
num.toString(); //"10"
num.toString(2); //"1010"
num.toString(8); //"12"
num.toString(10); //"10"
num.toString(16); //"a"

对普通对象来说,除非自行定义,否则toString() (Object.prototype.toString()) 返回内部属性[[Class]]的值,如'[object Object]', '[object Array]'。

所有安全的JSON值(JSON-safe)都可以使用JSON.stringify(..)字符串化。
不安全的JSON值包括undefined,function,symbol和包含循环引用的对象都不符合JSON结构标准,支持JSON的语言无法处理它们。

JSON.stringify(..)对象中 遇到undefined、function和symbol时会自动将其忽略,在数值中出现则会返回null(以保证单元位置不变)。

如果对象中定义了toJSON()方法,JSON字符串化时会首先调用该方法,然后用它的返回值来进行序列化。
toJSON() 应该"返回一个能够被字符串化的安全的JSON值",而不是"返回一个JSON字符串"。

JSON.stringify(..) 提供了replacer,和space参数。用来置顶对象序列化过程中那些属性应该被处理,哪些属性被忽略,并且支持space的缩进格式。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant