<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>深浅拷贝</title>
</head>
<body>
<script>
const person = {
name: 'Maike',
hobby: ['学习', ['篮球', '音乐']],
function(a) { console.log(a) },
date:new Date(),
say:undefined
}
/**浅拷贝 */
function clone(obj) {
const target = {}
for (let key in obj) {
if (!target.hasOwnProperty(key)) {
target[key] = obj[key]
};
};
return target
};
/** 深度拷贝 */
function deepClone(obj) {
const clone = Array.isArray(obj) ? [] : {};
if (obj && typeof obj === 'object') {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === 'object') {
clone[key] = deepClone(obj[key]);
} else {
clone[key] = obj[key];
};
};
};
return clone;
}
};
const person1 = clone(person);
const person2 = deepClone(person);
person1.name = "Kaelin"
person1.hobby[0] = '看电影'
console.log('person1', person1)
console.log('person', person)
console.log('person2', person2)
</script>
</body>
</html>
简单深浅拷贝
最新推荐文章于 2023-03-20 16:45:32 发布