JSON.stringify中你不知道的大坑

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值