使用toString()与JSON.stringify()相比有什么区别? [英] What's the difference in using toString() compared to JSON.stringify()?
问题描述
在这两种情况下,我都会输出对象的内容:
In both the cases I get in output the content of the object:
alert(JSON.stringify(obj));
或
alert(obj.toString());
所以...有什么区别?每个人的优点和缺点是什么?
so... what's the difference? what are the advantages or disadvantages of each one?
是否有实际例子来说明差异?
Are there practical examples to show the difference?
推荐答案
除非你有一个自定义对象,自定义 .toString
方法返回 JSON.stringify
该对象没有 obj
,它将给出 obj.toString()== JSON.stringify(obj)
。
Unless you have a custom object with custom .toString
method returning JSON.stringify
of that object, there is no obj
that would give obj.toString() == JSON.stringify(obj)
.
当 obj
是一个类似 [1,2,3]的数组时
然后 .toString()
给出:
When obj
is an array like [1,2,3]
then .toString()
gives:
"1,2,3"
和 JSON.stringify
:
"[1,2,3]"
这些是接近但不完全相同的,JSON序列化的一个没有逗号的歧义,直接作为Javascript运行或者可以解析为JSON。
These are close but not quite the same, the JSON serialized one has no ambiguity with commas and directly runs as Javascript or can be parsed as JSON.
参见:
["1,",2,3].toString();
//"1,,2,3" ... so you can't just split by comma and get original array
//it is in fact impossible to restore the original array from this result
JSON.stringify(["1,",2,3])
//'["1,",2,3]'
//original array can be restored exactly
这篇关于使用toString()与JSON.stringify()相比有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!