概念理解:
数组的解构赋值
对象的解构赋值
字符串的解构赋值
数值和布尔值的解构赋值
函数参数的解构赋值
数组的解构赋值:
一般的:
const arr=[1,2,3,4]; let [a,b,c,d]=arr; console.log(a,b,c,d) // 1 2 3 4
复杂点的:
const arr = [1, 2, [3, 4, [5, 6, 7]]]; const [, b] = arr; console.log(b) // 2
const [, , g] = [5, 6, 7]; console.log(g) // 7
const [, , [, , g]] = [3, 4, [5, 6, 7]]; console.log(g) // 7
const arr = [1, 2, [3, 4, [5, 6, 7]]]; const [, , [, , [, , g]]] = arr; console.log(g) // 7
const arr1 = [1, 2, 3]; const arr2 = ["a", "b"]; const arr3 = ["zz", 1]; const arr4 = [arr1, arr2, arr3]; console.log(arr4) // [[1,2,3],["a","b"],["zz",1]]
// 扩展运算符
const arr1 = [1, 2, 3]; const arr2 = ["a", "b"]; const arr3 = ["zz", 1]; // const arr4 = [arr1, arr2, arr3]; const arr4 = [...arr1, ...arr2, ...arr3]; console.log(arr4) // [1, 2, 3, "a", "b", "zz", 1]
const arr = [1, 2, 3, 4]; const [a, b, ...c] = arr; console.log(a,b,c) // 1 2 [3,4]
const arr = [1, undefined, undefined]; const [a, b, c, d] = arr; console.log(a, b, c, d) // 1 undefined undefined undefined
// 默认值
const [a, b = 2, c, d = "d"] = arr; console.log(a, b, c, d) // 1 2 undefined "d" ----有默认值的时候,如果右边对应的位置没有值,就用默认值,如果有值,用右边的值
// 交换变量 let a = 1; let b = 2; [a, b] = [b, a]; console.log([a, b]) // [2, 1]
对象的解构赋值:
const {a,b}={a:1,b:2}; console.log({a,b}) // {a: 1, b: 2}
新的对象的键名要和被解构对象的键名一样:
const obj={ name:"wql", age:23 }; const {name,age}=obj; console.log(name,age) // wql 23 console.log({name,age}) // {name: "wql", age: 23}
结合扩展运算符:
const obj={ name:"wql", age:23, sex:"男" }; const {name,...other}=obj; console.log(name,other) // wql {age: 23, sex: "男"}
字符串的解构赋值:
const str="i am a man"; const [a,b,c,...other]=str; console.log(a,b,c,other) // i a (7) ["m", " ", "a", " ", "m", "a", "n"]
函数参数的解构赋值:
function fn([x,y]){ return [y,x]; } let arr=[1,2]; arr=fn(arr); console.log(arr) // [2, 1]