变量的解构总结

es变量赋值的新写法

let a=1;
let b=2;
let c=3;
let d=4;

lat [a,b,c]=[1,2,3]

不完全解构、

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

报错的几种情况:

let [foo]=1;
let [foo]=false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {}

默认值

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

对象解构,对象解构没有秩序

let {foo, bar} = {foo:"aaa", bar:"bbb"}  // aaa, bbb

let obj={first: 'hello', second:'word'}
let {first:1, second:2} = obj;  //  first: hello; second: world

//嵌套解构
let obj = {
    p:[
        'hello',
        {
        y:'world'
        }
    ]
}

let {p:[x, {y}]} = obj;


字符串解构

[a,b,c,d,e,f] = 'hello'  

函数解构

[[1,2]. [3,4]].map(([a,b])=> a+b); // [3, 7]

用途

  1. 值交换

    let x=1;
    let y=2;
    [x,y]=[y,x]
    
    
  2. 从函数中返回多个值

    function example(){
        return {1,2,3}
    }
    let [a,b,c]=example(0;)
    
  3. 提取json

    let jsonData = {
        id:42,
        status:"OK",
        data:[876, 5309],
    }
    
    let {id, status, data, number} = jsonData;
    
  4. map的遍历

    var map=new Map()
    map.set('fist','hello');
    map.set('second','world');
    for(let [key, value] of map){
        console.log(key, value);
    }
    
    // 只遍历key
    for(let [key] of map){
        console.log(key);
    }
    
    // 只遍历value
    for(let [, value] of value){
        console.log(value);
    }
    

你可能感兴趣的:(变量的解构总结)