解构赋值

解构赋值语法是一种javascript表达式。可以将数组的值或者对象属性取出,赋值给其他变量。

首先解构赋值在项目中越来越常使用的一种赋值,常见的有数组和对象中获取来赋值。

数组解构:

let [a,b] = [1,2];
//a:1
//b:2

let [a,...b] = [1,2,3,4]
//a:1  
//b:[2,3,4] 由于是...扩展运算,跟数组合并的[...a,...b]相同,所以剩余属性都是b的

let arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];
// arr:[1, 3, 2] //这个为交换变量

//当没有这么多值后,其赋值为undefined
const foo = ['one', 'two'];
const [red, yellow, green, blue] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // undefined
console.log(blue);  //undefined  

对象解构:

let {a,b} = {a:1,b:2}
//a:1
//b:2

let [a = 1] = [];
let {b = 2} = {b: undefined}
let {c = 3} = {c: null}
let {d = 4} = {d: 5}
//a:1
//b:2
//c:3
//d:5
//首先不难理解,a=1为默认赋值,当其解构赋值数组为空时,或者对象为undefined、null时,则就会使用其默认值

let {a,...b} = {a: 1, b: 2, c: 3}
//a:1
//b:{b: 2, c: 3} 由于是...扩展运算,跟对象合并的{...a,...b}相同,所以剩余属性都是b的

const obj = {
  self: '123',
  __proto__: {
    prot: '456',
  },
};
const { self, prot } = obj;
// self "123"
// prot "456" (Access to the prototype chain) 还有就是获取属性的

其余的一些比较复杂,可以去官网参考,所以就一一复述了。
学会这些基本够用了。

posted @ 2023-01-09 15:32  夏季的雨  阅读(51)  评论(0)    收藏  举报