ECMAScript中变量的解构赋值

ECMAScript中变量的解构赋值

 

   ES6 允许从数组和对象中提取值,对变量进行赋值。

 

 解构赋值的基本用法:

    1、数组的解构赋值

  let [a, b, c]= [1,2, 3];

      console.log(a);//1

  console.log(b);//2

  console.log(c);//3

  

    2、对象的解构赋值

      let { foo:foo2, bar:bar2 } = {foo: "aaa",bar: "bbb" };
  console.log(foo2);// "aaa"
  console.log(bar2);// "bbb"

 

    3、字符串的解构赋值

     字符串也可以解构赋值。字符串可以被转换成了一个类似数组的对象。

    const [a, b, c, d, e]= 'hello';

     console.log(a);//h

   console.log(b);//e

   console.log(c);//l

     console.log(d);//l

    console.log(a);//hconsole.log(e);//o

 

     数组的对象都有一个length属性,因此还可以对这个属性解构赋值

  let{length : len}= 'hello'

      console.log(len)//5

    

     4.函数的解构赋值

    function add([x, y]){

    return x + y;

  }

  console.log(add([1,6])); // 7

  

   解构赋值的用途:

    1、交换变量的值

  let x=1;

      ley y=2;

      [x,y]=[y,x];

      console.log(x);//2

      console.log(y);//1

 

  2、从函数返回多个值

      function func1(){

        return [1,2,3]'

  }

      let [a,b,c]=func1();

      console.log(a);//1

      console.log(b);//2

      console.log(c);//3

 

   

 function func2() {
    return{
        foo:1,
        bar:2
    }
  }

 let {foo,bar}=func2();
 console.log(foo);//1
 console.log(bar);//2

3.函数参数的定义
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

4.提前json数据
解构赋值对提取JSON对象中的数据,尤其有用。
let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]


5.遍历Map结构
Map结构原生支持Iterator接口,配合变量的解构赋值,获取键名和键值就非常方便。
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world
如果只想获取键名,或者只想获取键值,可以写成下面这样。
// 获取键名 
for (let [key] of map) {
  // ... 
}  
// 获取键值 
for (let [,value] of map) {
  // ... 
} 

 

posted @ 2017-03-26 18:30  kerryqpw  阅读(308)  评论(0编辑  收藏  举报