1.浅拷贝分别用es3、es5、es6实现,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var obj = { a: 1, b: 2 }
// 浅拷贝
function simpleClone(obj) {
var cloneObj = {}
// es3写法
// for (var i in obj) {
// cloneObj[i] = obj[i]
// }
// es5写法一:
// Object.getOwnPropertyNames(obj).forEach(function (key) {
// cloneObj[key] = obj[key]
// })
// es5写法二:
// Object.getOwnPropertyNames(obj).forEach(function (key) {
// var desc = Object.getOwnPropertyDescriptor(obj, key)
// Object.defineProperty(cloneObj, key, desc)
// })
// es6写法一: 循环键名
// for (var key of Object.keys(obj)) {
// cloneObj[key] = obj[key]
// }
// es6写法二: 循环键值对
for (var [key, value] of Object.entries(obj)) {
cloneObj[key] = value
}
return cloneObj
}
console.log(simpleClone(obj)); // {a: 1, b: 2}
</script>
</body>
</html>
2.深拷贝分别用原生js、JSON.parse(JSON.stringify())、jQuery中$.extend方法实现,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
var obj = {
a: 1,
b: {
c: 3,
d: {
e: 5,
f: [1, 2, 3, 4, 5]
}
}
}
// 深拷贝
// 方法一: 原生js递归实现
function deepClone(obj, cloneObj) {
var cloneObj = cloneObj || {}
for (var i in obj) {
if (typeof obj[i] === 'object' && obj[i] !== null) {
// cloneObj[i] = Array.isArray(obj[i]) ? [] : {} // 方法一: Array.isArray
// cloneObj[i] = obj[i] instanceof Array ? [] : {} // 方法二: instanceof
cloneObj[i] = Object.prototype.toString.call(obj[i]) === '[object Array]' ? [] : {} // 方法三: Object.prototype.toString.call
deepClone(obj[i], cloneObj[i])
} else {
cloneObj[i] = obj[i]
}
}
return cloneObj
}
// 方法二: JSON.parse(JSON.stringify(obj)
// function deepClone(obj) {
// return JSON.parse(JSON.stringify(obj))
// }
// 方法三: 引入jQuery插件 src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"
// function deepClone(obj) {
// return $.extend(true, {}, obj);
// }
var obj1 = deepClone(obj)
obj.b.c = 10
obj.b.d.f.push(6)
console.log(obj);
console.log(obj1);
</script>
</body>
</html>