Skip to content
字数
394 字
阅读时间
2 分钟

JSON.stringfy 深度示例:

js
eg
	function deepClone(obj){
	let obj_ = JSON.stringify(obj),
	loneObj = JSON.parse(obj_);
	return loneObj
	}
	let a=[1,2,3,4],
	b=deepClone(a);
	b[0] = 2;
	console.log(a,b);

时间对象

如果 obj 里面有时间对象,则 JSON.stringify 后再 JSON.parse 的结果,时间将只是字符串的形式,而不是对象的形式

js
eg
	var test = {
	    name: 'a',
	    date: [new Date(1536627600000), new Date(1540047600000)],
	};  // 单纯用 new Date()没问题
	
	let b;
	b = JSON.parse(JSON.stringify(test));
	console.log(b); // {"name":"a","date":["2018-09-11T01:00:00.000Z","2018-10-20T15:00:00.000Z"]}

正则对象

如果 obj 里有 RegExp(正则表达式的缩写)、Error 对象,则序列化的结果将只得到空对象

js
eg
	const test = {
	    name: 'a',
	    date: new RegExp('\\w+'),
	};
	// debugger
	const copyed = JSON.parse(JSON.stringify(test));
	test.name = 'test'
	//console.error('ddd', test, copyed);
	console.log(copyed);  //  {"name":"a","date":{}}

对象中包含函数

如果 obj 里有函数,undefined,则序列化的结果会把函数或 undefined 丢失

js
eg
  const test = {
    name: 'a',
    date: function hehe() {
      console.log('fff')
    },
  };
  // debugger
  const copyed = JSON.parse(JSON.stringify(test));
  test.name = 'test'
  console.log('ddd', test, copyed); // ddd,{"name":"test"},{"name":"a"}

其他

  • 如果 obj 里有 NaN、Infinity 和 -Infinity,则序列化的结果会变成 null

  • 如果对象中存在循环引用的情况也无法正确实现深拷贝

  • JSON.stringify() 只能序列化对象的可枚举的自有属性

例如 如果 obj 中的对象是有构造函数生成的, 则使用 JSON.parse(JSON.stringify(obj)) 深拷贝后,会丢弃对象的 constructor;

js
eg:
	function Person(name) {
	this.name = name;
	console.log(name)
	}
	
	const liai = new Person('liai');
	
	const test = {
	name: 'a',
	date: liai,
	};
	// debugger
	const copyed = JSON.parse(JSON.stringify(test));
	test.name = 'test'
	console.log('ddd', test, copyed)
	// > liai
    // > ddd,{"name":"test","date":{"name":"liai"}},{"name":"a","date":{"name":"liai"}}

总结

JSON.parse(JSON.stringfy(X)),其中 X 只能是 Number, String, Boolean, Array, 扁平对象,即那些能够被 JSON 直接表示的数据结构

贡献者

The avatar of contributor named as jiechen jiechen

页面历史

撰写