Parse, json. stringify Depth copy defects
Parse and stringify can be used with deep-copy objects, but they may not notice some defects. Once I used them to deep-copy objects, I found that some properties were inexplicably missing. I hadn’t looked into the defects too deeply before. Take the time today to delve into these drawbacks.
First let’s look at the code:
let deepClone = function(obj) {
return JSON.parse(JSON.stringify(obj))
}
let a = {
name: 'Ken'.age: 18.hobbit: ['dance'.'sing', {type: 'sports'.value: 'run'}].schoolData: {
grades: 'A',},run: function() {},
walk: undefined.fly: NaN.cy: null
}
let b = deepClone(a)
console.log("b", b)
/ * * {age: 18, cy: null, fly: null, hobbit: (3) [" dance ", "sing", {...}], name: "Ken", schoolData: {grades: "A"},} * * /
Copy the code
Compared with the original object, we can know:
- Does not copy key-value pairs on objects whose value is undefined and functions
- NaN, infinity, infinitesimal will be null
Custom object tests
let Ken = function() {
this.name = "Ken"
}
Ken.prototype.walk = function() {
console.log("walk")}let KenNaNa = function() {
Ken.call(this.arguments)
this.name = "KenNaNa"
}
let tempFunc = function() {}
tempFunc.prototype = Ken.prototype
KenNaNa.prototype = new tempFunc()
KenNaNa.prototype.age = "18"
KenNaNa.prototype.run = function() {
console.log("run")}Object.defineProperty(KenNaNa.prototype, "contructor", {
value: KenNaNa,
enumerable:false
})
let kenNaNa = new KenNaNa()
let copyKenNaNa = JSON.parse(JSON.stringify(kenNaNa))
/** Ken {age: "18", run: ƒ, ƒ} ** /
console.log(copyKenNaNa.constructor); ƒ Object() {[native code]}
console.log(copyKenNaNa.age) // undefined
console.log(copyKenNaNa.run()) // is not function
console.log(copyKenNaNa.walk()) // is not function
console.log(copyKenNaNa.toString()) // "[object Object]"
Copy the code
- Can not get the prototype above the method, the attribute, can only get the Object prototype content
var date = new Date(a)var copy = JSON.parse(JSON.stringify(date))
console.log("copy", copy) / / "the 2021-01-14 T06: fast now. 337 z"
Copy the code
conclusion
- The key whose value is undefined cannot be obtained
- NaN and infinity, infinitesimal converted to NULL
- The contents of the prototype cannot be retrieved
- A date object is converted to a date string