es6(基礎二) 變量的解構賦值

前言:

    ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱爲解構

    1.左右兩邊結構必須一樣
    2.右邊必須是個東西
    3.聲明和賦值不能分開(必須在一句話裏完成)

一、數組的解構賦值

    1.格式:let [a,b,c] = [1,2,3]

    es6之前的賦值

{
    var arr = [1,2,3];
    var a,b,c;
    a = arr[0];
    b = arr[b];
    c = arr[c];
}

    es6的賦值

{
    let arr = [1,2,3];
    let [a,b,c] = arr;
    console.info(a,b,c);//1 2 3 
}
   2. 注意:

            1).如果匹配不到,則變量值是undefined

{
    let [a,b,c] = [1,2];
    console.info(a,b,c);//1 2 undefined
}
{
    const [a,b,c] = [1,2];
    console.info(a,b,c);//1 2 undefined
}
            2)如果等號的右邊不是數組(或者嚴格地說,不是可遍歷的結構),那麼將會報錯
//要求是可iterator的數、並且左右兩邊的數據類型要一致,比如都是數組或者都是對象
{
    let [num] = {
        num:1,
	str:"2"
    };
    console.info(num);//報錯
}

    3.默認值(當要賦值的值嚴格等於undefined時,默認值生效)

{
	let [a=true] = [];
	console.info(a);//true
	let [b=true] = [undefined];
	console.info(b);//true 
	let [c=true] = [null];
	console.info(c);//null
	let [d=true] = [1];
	console.info(d);//1
}

    4.rest(...)

/*...相當於餘下的所有值組成的數組*/
{
	let [a,b,...c] = [1,2,3,4,5,7,7]
	console.info(a,b,c);//1 2 (5) [3, 4, 5, 7, 7]
	c.push("aaa");
	console.info(c);//(6) [3, 4, 5, 7, 7, "aaa"]
}

    5.實戰

{
    // 交換變量
    let a=1;
    let b=2;
    [a,b]=[b,a]
    console.log(a,b);// 2 1
}

二、對象的解構賦值

    1.格式:let {a,b,c} = {a:1,b:2,c:3} 是通過key來匹配的,而不是根據順序

                對象的解構賦值的內部機制,是先找到同名屬性,然後再賦給對應的變量

{
	let {a,b} = {a:1,b:2};
	console.info(a,b);//1 2 
}
{
	let {a,b} = {aaa:3,b:4};
	console.info(a,b);// undefined 4
}{
	let {a,b} = {b:4,a:3};
	console.info(a,b);//3 4
}{
	let {foo:a} = {foo:'aaa'};
	//console.info(foo);//foo是模式,報ReferenceError
	console.info(a);//aaa
}

    2.嵌套結構的賦值

{
	let obj = {
		p:[
			'hello',
			{y:"world"}
		]
	}
	let {p:[x,{y}]} = obj;
	console.info(x,y);//hello world
}  

    3.默認值(默認值生效的條件是,對象的屬性值嚴格等於undefined)

{
	let {a=true} = {a:1};
	console.log(a);//1
}
{
	let {a=true} = {a:undefined};
	console.log(a);//true
}
{
	let {a=true} = {a:null};
	console.log(a);//null
}

三、字符串解構賦值

    1.格式:let [a,b,c] = '123' 字符串被轉換成了一個類似數組的對象

{
	let [a,b] = 'hello';
	console.info(a,b);// h 3 
}
{
	let [a,b,c] = 'h2';
	console.info(a,b,c);//h 2 undefined
}

    2.帶有的length,toString等屬性

{
	let {length:len} = "hello";
	console.info(len);//5
}
{
	let {toString:a} = 12;
	console.info(a);//ƒ toString() { [native code] }
	console.info(a===Number.prototype.toString);//true
}

四、函數解構賦值

{
	function fn([a,b]){
		return a+b;
	}
	console.log(fn([3,1]));//4
}
{
	function fn(){
		return [1,2]
	}
	let a,b;
	[a,b] = fn();
	console.info(a,b);//1 2 
}
{
	function fn(){
		return [1,2,3,4,5,6,7]
	}
	//let a,b,c;
	let [a,,,b,...c] = fn();
	console.info(a,b,c);//1 4 (3) [5, 6, 7]
}


  
發佈了23 篇原創文章 · 獲贊 3 · 訪問量 2637
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章