本文摘自PHP中文网,作者Guanhui,侵删。

JS 深拷贝的三种实现方式
1、将对象转换为JSON字符串形式,再将其转换为原生JS对象;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | let deepClone = function (obj) {
let _tmp = JSON.stringify(obj);
let result = JSON.parse(_tmp);
return result;
};
let obj1 = {
weiqiujaun: {
age: 20,
class: 1502
},
liuxiaotian: {
age: 21,
class: 1501
}
};
let test = deepClone(obj1);
console.log(test);
|
2、使用JS中的for循环实现遍历和复制;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function deepClone(obj) {
let result = typeof obj.splice === "function" ? [] : {};
if (obj && typeof obj === 'object' ) {
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object' ) {
result[key] = deepClone(obj[key]);
} else {
result[key] = obj[key];
}
}
return result;
}
return obj;
}
let testArray = [ "a" , "b" , "c" , "d" ];
let testRes = deepClone(testArray);
console.log(testRes);
console.log( typeof testRes[1]);
let testObj = {
name: "weiqiujuan" ,
sex: "girl" ,
age: 22,
favorite: "play" ,
family: {brother: "son" , mother: "haha" , father: "heihei" }
};
let testRes2 = deepClone(testObj);
testRes2.family.brother = "weibo" ;
console.log(testRes2);
|
3、利用数组的“Array.prototype.forEach”方法进行复制即可实现深拷贝。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | let deepClone = function (obj) {
let copy = Object.create(Object.getPrototypeOf(obj));
let propNames = Object.getOwnPropertyNames(obj);
propNames.forEach( function (items) {
let item = Object.getOwnPropertyDescriptor(obj, items);
Object.defineProperty(copy, items, item);
});
return copy;
};
let testObj = {
name: "weiqiujuan" ,
sex: "girl" ,
age: 22,
favorite: "play" ,
family: {brother: "wei" , mother: "haha" , father: "heihei" }
}
let testRes2 = deepClone(testObj);
console.log(testRes2);
|
推荐教程:《JS教程》
以上就是JS 深拷贝的三种实现方式的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
vue+axios+PHP如何实现上传文件功能?
使用PHP和html5 formdata实现无刷新文件上传
jquery 遍历parent()方法
html5+javascript进行邮箱地址验证
html5入门之设计原理解析
ajax请求的五个步骤
jquery里面能不能写PHP方法?
在 js 中使用类似 PHP 的魔术方法
快速掌握前端开发技巧
js 深拷贝的三种实现方式
更多相关阅读请进入《PHP》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » JS 深拷贝的三种实现方式