What's the difference in using toString() compared to JSON.stringify()?

前端 未结 4 874
北荒
北荒 2020-12-08 04:28

In both the cases I get in output the content of the object:

alert(JSON.stringify(obj));

or

alert(obj.toString());
<         


        
4条回答
  •  再見小時候
    2020-12-08 04:55

    for an object say

    obj = { a: 'a', '1': 1 }
    

    obj.toString() gives

    "[object Object]"
    

    JSON.stringify(obj) gives

    "{"1":1,"a":"a"}"
    

    For .toString(), a default value is returned when the argument type is an object. JSON.stringify on the other hand returns JSON text, which can be converted back into a JSON object by using JSON.parse

提交回复
热议问题