Web/06-JavaScript进阶/02-数据的赋值.md
2020-07-31 22:07:19 +08:00

61 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 对象赋值
### Object.assgin() 实现浅拷贝
代码举例
```js
const obj1 = {
name: 'qianguyihao',
age: 28,
desc: 'hello world',
};
const obj2 = {
name: '许嵩',
sex: '男',
};
// 【关键代码】浅拷贝:把 obj1 赋值给 obj2。这行代码的返回值也是 obj2
Object.assign(obj2, obj1);
console.log(JSON.stringify(obj2));
```
打印结果
```
{"name":"qianguyihao","sex":"男","age":28,"desc":"hello world"}
```
注意**上面这行代码在实际开发中会经常遇到一定要掌握**它的作用是 obj1 的值追加到 obj2 如果两个对象里的属性名相同 obj12 中的值会被 obj2 中的值覆盖
## 数组赋值
### 扩展运算符
```js
arr2 = arr1;
```
上方代码中其实是让 arr2 指向 arr1 的地址也就是说二者指向的是同一个内存地址
如果不想让 arr1 arr2 指向同一个内存地址我们可以借助扩展运算符来做
```javascript
let arr2 = [...arr1]; //arr2 会开辟新的内存地址
```
参考链接
- [javaScript中浅拷贝和深拷贝的实现](https://github.com/wengjq/Blog/issues/3)