你不知道的 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}"

 

 

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