-
Notifications
You must be signed in to change notification settings - Fork 0
/
Object.assign().html
52 lines (44 loc) · 1.42 KB
/
Object.assign().html
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
/*
Object.assign()
用于将所有可枚举属性的值从一个或多个源对象复制到目标对象并返回目标对象。
Object.assign(target, ...sources)
参数:
target(目标对象)
sources(源对象)
返回值:
目标对象
Object.assign方法实行的是浅拷贝,而不是深拷贝
1.Object.assign()拷贝的是属性值。假如源对象的属性值是一个指向对象的引用,它也只拷贝那个引用值。
2.遇到同名属性,Object.assign的处理方法是替换,而不是添加。
*/
//浅拷贝
let obj = {a:1,b:2,c:{d:3}}
let obj1 = Object.assign({},obj)
obj.a = 2;
obj.c.d = 4;
console.log(obj) //{a:2,b:2,c:{d:4}}
console.log(obj1) //{a:1,b:2,c:{d:4}}
//同名替换
let obj2 = {a:1,b:2,c:3}
let obj3 = {a:1,b:2,c:4}
let obj4 = {a:1,b:2,c:5}
let obj5 = Object.assign(obj2,obj3,obj4)
console.log(obj2,obj3,obj4) //注意目标对象自身也会改变,除目标参数外其它无变化
console.log(obj5) //{a:1,b:2,c:5}
let o1 = {a:1,b:2,c:3}
let o2 = {a:1,b:2,c:4}
let o3 = {a:1,b:2,c:5}
let o4 = Object.assign({},o1,o2,o3)
console.log(o1,o2,o3)
console.log(o4) //{a:1,b:2,c:5}
</script>
</body>
</html>