解构
- 解构赋值是对赋值运算符的扩展。
- 是一种针对数组或者对象进行模式匹配,然后对其中的变量进行赋值。
- 在代码书写上简洁且易读,语义更加清晰明了;也方便了复杂对象中数据字段获取。
在解构中,有下面两部分参与:
- 解构的源,解构赋值表达式的右边部分。
- 解构的目标,解构赋值表达式的左边部分。
数组
- 基本
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); //1 2 3
- 可嵌套
let [a, [[b], c]] = [1, [[2], 3]];
console.log(a, b, c); //1 2 3
- 可忽略
let [a, , b] = [1, 2, 3];
console.log(a, b); //1 3
- 不完全解构
let [a = 1, b] = []; // a = 1, b = undefined
- 剩余运算符
let [a, ...b] = [1, 2, 3];
console.log(a, b); //a = 1, b = [2,3]
- 字符串
在数组的解构中,解构的目标若为可遍历对象,皆可进行解构赋值。可遍历对象即实现 Iterator 接口的数据。
let [a, b, c, d, e] = 'hello';
console.log(a, b, c, d, e); //h e l l o
- 解构默认值
let [a = 2] = [undefined]; // a = 2
当解构模式有匹配结果,且匹配结果是 undefined 时,会触发默认值作为返回结果。
let [a = 3, b = a] = []; // a = 3, b = 3
let [a = 3, b = a] = [1]; // a = 1, b = 1
let [a = 3, b = a] = [1, 2]; // a = 1, b = 2
- a 与 b 匹配结果为 undefined ,触发默认值:a = 3; b = a =3
- a 正常解构赋值,匹配结果:a = 1,b 匹配结果 undefined ,触发默认值:b = a =1
- a 与 b 正常解构赋值,匹配结果:a = 1,b = 2
对象
- 基本
let { foo, bar } = { bar: 'bbb' , foo: 'aaa'};
// foo = 'aaa'
// bar = 'bbb'
let { baz : foo } = { baz : 'ddd' };
// foo = 'ddd'
- 可嵌套可忽略
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { y }] } = obj;
// x = 'hello'
// y = 'world'
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { }] } = obj;
// x = 'hello'
- 不完全解构
let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;
// x = undefined
// y = 'world'
- 剩余运算符
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}
- 解构默认值
let {a = 10, b = 5} = {a: 3};
// a = 3; b = 5;
let {a: aa = 10, b: bb = 5} = {a: 3};
// aa = 3; bb = 5;
扩展运算符
数组
- 复制数组:
let arr = [1, 2],
arr1 = [...arr];
console.log(arr1); // [1, 2]
// 数组含空位
let arr2 = [1, , 3],
arr3 = [...arr2];
console.log(arr3); [1, undefined, 3]
- 合并数组:
console.log([...[1, 2],...[3, 4]]); // [1, 2, 3, 4]
对象
拓展运算符(...)用于取出参数对象所有可遍历属性然后拷贝到当前对象。
- 基本用法
let person = {name: "Amy", age: 15};
let someone = { ...person };
console.log(someone); //{name: "Amy", age: 15}
- 可用于合并两个对象
let age = {age: 15};
let name = {name: "Amy"};
let person = {...age, ...name};
console.log(person); //{age: 15, name: "Amy"}
注意:自定义的属性和拓展运算符对象里面属性的相同的时候
- 自定义的属性在拓展运算符后面,则拓展运算符对象内部同名的属性将被覆盖掉。
let person = {name: "Amy", age: 15};
let someone = { ...person, name: "Mike", age: 17};
console.log(someone); //{name: "Mike", age: 17}
- 自定义的属性在拓展运算度前面,则变成设置新对象默认属性值。
let person = {name: "Amy", age: 15};
let someone = {name: "Mike", age: 17, ...person};
console.log(someone); //{name: "Amy", age: 15}
- 拓展运算符后面是空对象,没有任何效果也不会报错。
let a = {...{}, a: 1, b: 2};
console.log(a); //{a: 1, b: 2}
- 拓展运算符后面是null或者undefined,没有效果也不会报错。
let b = {...null, ...undefined, a: 1, b: 2};
console.log(b); //{a: 1, b: 2}
标签:...,console,log,扩展,解构,运算符,let
From: https://www.cnblogs.com/Kongqingzhi/p/16622606.html