你不知道的 JavaScript 系列中( 24 ) - toString()和JSON.stringify()

undefined.toString(); // TypeError: Cannot read property 'toString' of undefined

null.toString(); // TypeError: Cannot read property 'toString' of null

true.toString(); // "true"

111..toString(); // "111"

[1,2,3].toString(); // "1,2,3"

undefined/null 是一個原始值 不是對象 就沒有原型 就調用不到Object.prototype(原型鏈最終原型)的 toString 方法。c,d,e會強制轉化,調用其對應的Boolean.toString(),Number.toString(),Array.toString();

 

JSON.stringify(undefined); // undefined

JSON.stringify(null); // "null"

JSON.stringify(true); // "true"

JSON.stringify(111); // "111"

JSON.stringify([1,2,3]) // "[1,2,3]"

所有安全的 JSON 值(JSON-safe)都可以使用 JSON.stringify(..) 字符串化。不安全的 JSON 值。undefined、function、symbol (ES6+)和包含循環引用(對象之間相互引用,形成一個無限循環)的對象都不符合 JSON 結構標準,支持 JSON 的語言無法處理它們

JSON.stringify( undefined ); // undefined

JSON.stringify( function(){} ); // undefined

JSON.stringify( [1,undefined,function(){},4]); // "[1,null,null,4]"

JSON.stringify({ a:2, b:function(){} }); // "{"a":2}"

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章