浅拷贝:Object.assign(target, ...sources)。
**Object.assign()**
:方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象,它将返回目标对象。
<!-- 补充:数组也可以用for ... in -->
<script>
var arr = ['pink', 'red', 666]
for (var k in arr) {
console.log(k); // 0 1 2
console.log(arr[k]); // pink red 666
}
</script>
<!-- 浅拷贝 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 浅拷贝只是拷贝一层, 更深层次对象级别的只拷贝引用.
// 深拷贝拷贝多层, 每一级别的数据都会拷贝.
var obj = {
id: 1,
name: 'andy',
msg: {
age: 18
}
};
var o = {};
for (var k in obj) {
// k 是属性名 obj[k] 属性值
o[k] = obj[k];
}
console.log(o); // {id: 1, name: "andy", msg: {…}}
o.msg.age = 20;
console.log(obj); // {id: 1, name: "andy", msg: {…}}
console.log('--------------');
Object.assign(o, obj);
console.log(o); // {id: 1, name: "andy", msg: {…}}
o.msg.age = 20;
console.log(obj); // {id: 1, name: "andy", msg: {…}}
</script>
</body>
</html>
<!-- 深拷贝 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 深拷贝拷贝多层, 每一级别的数据都会拷贝.
var obj = {
id: 1,
name: 'andy',
msg: {
age: 18
},
color: ['pink', 'red']
};
var o = {};
// 封装函数
function deepCopy(newobj, oldobj) {
for (var k in oldobj) {
// 判断我们的属性值属于那种数据类型
// 1. 获取属性值 oldobj[k]
var item = oldobj[k];
// 2. 判断这个值是否是数组
if (item instanceof Array) {
newobj[k] = [];
deepCopy(newobj[k], item)
} else if (item instanceof Object) {
// 3. 判断这个值是否是对象
newobj[k] = {};
deepCopy(newobj[k], item)
} else {
// 4. 属于简单数据类型
newobj[k] = item;
}
}
}
deepCopy(o, obj);
console.log(o); // {id: 1, name: "andy", msg: {…}, color: Array(2)}
o.msg.age = 20;
console.log(obj); // {id: 1, name: "andy", msg: {…}, color: Array(2)}
var arr = [];
console.log(arr instanceof Object); // true
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/jianjie/p/12232179.html
时间: 2024-10-13 23:41:38