变量的解构赋值

  1. 理解:
  • 从对象或数组中提取数据, 并赋值给变量(多个)
  1. 对象的解构赋值
    let {n, a} = {n:'tom', a:12}
  2. 数组的解构赋值
    let [a,b] = [1, 'hello'];
  3. 用途
  • 给多个形参赋值
let obj = {username: 'kobe', age: 40};
    // let username = obj.username;
    // let age = obj.age;
    // let {username, age} = obj;
    // console.log(username, age);
    // let {age} = obj;
    // console.log(age);
    let arr = [1,3,5,'abc',true];
    // let [a,b,c,d,e] = arr;
    // console.log(a,b,c,d,e);
    let [,,a,b] = arr;
    console.log(a,b);
    /*function foo(obj){
        console.log(obj.username, obj.age);
    }*/
    function foo({username, age}){//{username, age} = obj;
        console.log(username, age);
    }
    foo(obj);

你可能感兴趣的:(变量的解构赋值)