let obj = { val: undefined, a: NaN, b: Infinity, c: new Date(), d: { e: 'nice' }, y: Object } console.log(JSON.stringify(obj)) //輸出 "{ "a": null, "b": null, "c": "2019-03-13T12:01:44.295Z", "d": "{ "e": "nice" }" }"
當對象的value
爲undefined
和Object
時會被忽略,爲NaN和Infinity爲null,對象實例如d
,爲key
和value
都加上雙引號數組
let arr = [undefined, Object, Symbol(""), { e: 'nice' }] console.log(JSON.stringify(arr)) //輸出 "[null, null, null, { "e": "nice" }]"
當成員爲undefined
、Object
、Symbol
時爲null,對象也是爲key
和value
都加上雙引號this
能夠重寫toJSON()
方法進行自定義序列化code
let obj = { x: 1, y: 2, re: { re1: 1, re2: 2, toJSON: function(){ return this.re1 + this.re2; } } } console.log(JSON.stringify(obj)) //輸出 "{ "x":1, "y":2, "re":3 }"
let obj = { x:1, y:2 } console.log(obj.toString()) //輸出 "[object Object]" obj.toString = function(){ return this.x + this.y; } "Result" + obj; //輸出 "Result3" 調用了toString +obj; //輸出 "3" 調用了toString obj.valueOf = function(){ return this.x + this.y + 100; } "Result" + obj; //輸出 "Result103" 調用了toString
當toString
和valueOf
都存在時,在進行操做時,都會嘗試轉換成基本類型,先找valueOf
,若是返回基本類型,這隻調用valueOf
,若是不是,好比是對象的話,就去找toString
,若是也返回Object,就會報錯對象