js深拷贝
Posted zengsm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js深拷贝相关的知识,希望对你有一定的参考价值。
<script> function deepClone(obj) { if (typeof obj != ‘object‘ || obj == null) { return obj; } let result; if (obj instanceof Array) { result = []; } else { result = {}; } for (const key in obj) { if (obj.hasOwnProperty(key)) { const element = obj[key]; result[key] = deepClone(element); } } return result; } let obj = { name: "伍子胥", girl: { name: ‘any‘, items: [1, 2, 3] } }; let obj2 = deepClone(obj); obj2.girl.name = ‘abc‘; obj2.girl.items[0] = 999; console.log(obj.girl.name); console.log(obj.girl.items[0]); </script>
以上是关于js深拷贝的主要内容,如果未能解决你的问题,请参考以下文章