在这两种情况下,我都会输出对象的内容:
alert(JSON.stringify(obj));
或
alert(obj.toString());
所以...有什么区别?各自的优缺点是什么?
有实际例子可以说明区别吗?
最佳答案
除非您有一个带有自定义 .toString
方法的自定义对象返回该对象的 JSON.stringify
,否则没有 obj
会给出obj.toString() == JSON.stringify(obj)
。
当 obj
是像 [1,2,3]
这样的数组时,.toString()
给出:
"1,2,3"
和JSON.stringify
:
"[1,2,3]"
这些很接近但不完全相同,JSON 序列化的没有逗号歧义,直接作为 Javascript 运行或者可以作为 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
关于javascript - 与 JSON.stringify() 相比,使用 toString() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15834172/