JavaScript对象克隆:使用Object.assign()解决属性差异问题
openEdit(obj) {\n // 克隆对象 克隆了再用\n let newObjj = JSON.parse(JSON.stringify(obj))\n this.editSpot = newObjj\n this.editSpot.recommend = this.editSpot.recommend === 1\n console.info(obj)\n console.info(newObjj)\n this.dialogFormVisible = true\n},克隆完newObjj 与obj的属性有一个不一样内容:The issue might be with the cloning process. When you use JSON.parse(JSON.stringify(obj)) to clone an object, it creates a new object with the same properties and values as the original object. However, there are some cases where this method doesn't work as expected.\n\nOne possible reason for the properties being different is that the original object might contain non-enumerable properties or methods that are not cloned using this method. To overcome this issue, you can use Object.assign() instead of JSON.parse(JSON.stringify(obj)) to clone the object.\n\nHere's an updated version of the code using Object.assign(): \n\njavascript\nopenEdit\(obj\) {\n // Cloning the object using Object.assign()\n let newObj \= Object.assign\({}, obj\);\n this.editSpot \= newObj;\n this.editSpot.recommend \= this.editSpot.recommend === 1;\n console.info\(obj\);\n console.info\(newObj\);\n this.dialogFormVisible \= true;\n}\n\n\nBy using Object.assign(), all enumerable properties and methods of the original object will be cloned to the new object accurately.
原文地址: https://www.cveoy.top/t/topic/p0Ik 著作权归作者所有。请勿转载和采集!