ES6變數解構賦值的用法

2022-07-27 04:42:13 字數 2606 閱讀 8146

一、陣列賦值(從陣列中提取值,按照對應位置,對變數賦值)

1. 完全解構(變數與值數目相等)

let arr = [1, 2, 3];

let [a,b,c] =arr;

console.log(a, b, c);

//1 2 3

2. 不完全解構(變數的數目小於值的數目)

let arr = [1, 2, 3, 4];

let [a,b,c] =arr;

console.log(a, b, c);

//1 2 3

3. 解構不成功(變數的數目大於值的數目)

let arr = [1, 2];

let [a,b,c] =arr;

console.log(a, b, c);

//1 2 undefined

備註:以上三種情況都可以給變數賦上值。

4. 預設值

預設值生效的條件是,變數嚴格等於undefined

let arr = [1, 2];

let [a,b,c = 3] =arr;

console.log(a, b, c);

//1 2 3

let arr = [1, 2, undefined];

let [a,b,c = 3] =arr;

console.log(a, b, c);

//1 2 3

let arr = [1, 2, null

]; let [a,b,c = 3] =arr;

console.log(a, b, c);

//1 2 null

如果預設值是乙個表示式,那麼這個表示式是惰性求值的,即只有在用到的時候,才會求值。

function

fun ()

let [x = fun()] = [1];

console.log(x); //1

// fun不會執行

function

fun ()

let [x = fun()] =[undefined];

console.log(x);

//hhhhhhhhhhh undefined

// fun會執行

5. 預設值可以引用解構賦值的其他變數,但該變數必須已經宣告。

let [x = 1, y = x] = ;     //

x=1; y=1

let [x = 1, y = x] = [2]; //

x=2; y=2

let [x = 1, y = x] = [1, 2]; //

x=1; y=2

let [x = y, y = 1] = ; //

y is not defined

二、物件的解構賦值(陣列是按順序,但是物件直接賦值需要按屬性名來賦值)

1.  變數名即是屬性名

let obj =;

let =obj;

console.log(name, age); // lqw 23

2. 變數名不是屬性名

let obj =;

let =obj;

console.log(a, b);

//lqw 23

其實物件的賦值是下面形式的簡寫(物件的解構賦值的內部機制,是先找到同名屬性,然後再賦給對應的變數。真正被賦值的是後者,而不是前者。)

let  = ;

console.log(a, b);

//lqw 23

三、字串解構賦值

let [a, b, c] = 'lqw';

console.log(a, b, c);

//l q w

四、數值和布林值的解構賦值

解構賦值時,如果等號右邊是數值和布林值,則會先轉為物件。

let  = 123;

s === number.prototype.tostring //

true

let = true

;s === boolean.prototype.tostring //

true

上面**中,數值和布林值的包裝物件都有tostring屬性,因此變數s都能取到值。

解構賦值的規則是,只要等號右邊的值不是物件或陣列,就先將其轉為物件。由於undefinednull無法轉為物件,所以對它們進行解構賦值,都會報錯。

let  = undefined; //

typeerror

let = null; //

typeerror

五、函式引數的解構賦值 

function

add([x, y])

add([1, 2]); //

3

es6變數解構賦值

es6允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為解構。解構賦值在實際開發中可以大量減少我們的 量,並且讓我們的程式結構更清晰。陣列的解構賦值 let a,b 1 2 console.log a 1 console.log b 2 上面的 表示,可以從陣列中提取值,按照位置的物件...

ES6變數解構賦值

es6 允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為解構 es6之前我們申明多個變數需要按照下面的方法 let l a 1 let b 2 let c 3 let d 4 或者 let a 1,b 2,c 3,d 4 現在我們可以更加簡便 let a,b,c,d 1,2,3,4 ...

es6 變數解構賦值

1.陣列的解構賦值 等號兩邊的模式相同,左邊的變數就會被賦予對應的值 預設值 undefined型別只有乙個值,即undefined。當宣告的變數還未被初始化時,變數的預設值為undefined。null型別也只有乙個值,即null。null用來表示尚未存在的物件,常用來表示函式企圖返回乙個不存在的...