61 lines
1.2 KiB
JavaScript
61 lines
1.2 KiB
JavaScript
|
||
|
||
## 对象赋值
|
||
|
||
|
||
### 用 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)
|
||
|
||
|