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.parse() 与 JSON.stringify() #43

Open
lmk123 opened this issue May 27, 2016 · 0 comments
Open

你不知道的 JSON.parse() 与 JSON.stringify() #43

lmk123 opened this issue May 27, 2016 · 0 comments

Comments

@lmk123
Copy link
Owner

lmk123 commented May 27, 2016

众所周知,这两个方法用于在字符串与对象之间进行转换。其中用到的最多的场景就是在保存数据到 localStorage 里的时候——因为 localStorage 里只能保存字符串,所以当我们想要保存对象进去时,就会先 JSON.stringify() 一下,读取出来时,再 JSON.parse() 一下。

但是,这样做很可能会产生 bug!

先来看下面这段代码:

JSON.parse('100');

一定是我书读的少的缘故,我一直认为上面这段代码会报错——因为字符串 '100' 并不是一个 JSON 字符串。

但是实际上,这段代码不会报错,而是会返回 Number 类型的 100

同理还有 JSON.stringify(100),这段代码同样不会报错,而是会返回字符串类型的 '100'查看完整的在线示例

强烈推荐完整的阅读一下 MDN 上关于这两个方法的说明:

MDN - JSON.stringify()
MDN - JSON.parse()

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

No branches or pull requests

1 participant