let res = JSON.stringify({
a: undefined,
b: null,
c: function(){},
d: false,
e: NaN,
f: Infinity,
g: {
name: '小雨雨'
},
h: Symbol('foo')
})
console.log(res) // {"b":null,"d":false,"e":null,"f":null,"g":{"name":"小雨雨"}}
// undefined, 函数, Symbol 会被忽略; NaN,Infinity会被置换为null
let obj = {
name: '小雨雨'
}
obj.a = obj;
const res2 = JSON.stringify(obj);
console.log(res2);
// index.html:34 Uncaught TypeError: Converting circular structure to JSON
// --> starting at object with constructor 'Object'
// --- property 'a' closes the circle
// at JSON.stringify (<anonymous>)
// 对象属性嵌套自身转换时会报错
const alsoHuge = BigInt(9007199254740991)
console.log(JSON.stringify(alsoHuge))
// TypeError: Do not know how to serialize a BigInt
const arr = [undefined, Symbol('foo'), null, false, NaN,
function(){}, Infinity, {}, [], 0, true];
console.log(JSON.stringify(arr)) // [null,null,null,false,null,null,null,{},[],0,true];
// 在数组中 undefined, Symbol, NaN,函数,Infinity都会转换为null
JSON.stringify中你不知道的大坑
最新推荐文章于 2024-05-22 14:06:40 发布