Web/07-JavaScript进阶/02-数据的赋值.md
2021-11-17 11:47:05 +08:00

74 lines
1.3 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.

---
title: 02-数据的赋值
publish: true
---
<ArticleTopAd></ArticleTopAd>
## 对象赋值
### 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 如果两个对象里的属性名相同 obj2 中的值会被 obj1 中的值覆盖
## 数组赋值
### 扩展运算符
```js
arr2 = arr1;
```
上方代码中其实是让 arr2 指向 arr1 的地址也就是说二者指向的是同一个内存地址
如果不想让 arr1 arr2 指向同一个内存地址我们可以借助扩展运算符来做
```javascript
let arr2 = [...arr1]; //arr2 会开辟新的内存地址
```
参考链接
- [javaScript中浅拷贝和深拷贝的实现](https://github.com/wengjq/Blog/issues/3)