es6-- let const 解构赋值

let

1.块级作用域中有效
2.不能重复定义
3.es6强制开启"use strict"

const

  1. 声明时候必须赋值
  2. 常量,不能修改值
  3. 声明对象,可以修改, 不能修改的是栈内存在地址

var声明的变量,其作用域为该语句所在的函数内,且存在变量提升现象;
let声明的变量,其作用域为该语句所在的代码块内,不存在变量提升;

function test(){
  const PI = 3.1415926;
  // PI = 123; //不能修改值
  const k = { a:1}
  //对象本身是可以变的
  k.b = 3;
  console.log(k); // {a:1, b:3}
}

解构赋值

数组解构赋值, 对象解构赋值, 字符串解构赋值, 布尔值解构赋值, 数值解构赋值
函数参数解构赋值

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。

 // 数组解构赋值
{
  let a, b, c, reset;
  [a, b] = [2, 3];// 2, 3
  [a, b, ...rest] = [2, 3, 4, 5, 6, 7];// 2, 3, [4,5,6,7]
  ({a, b} = {a:1, b:2});// 1,2
  [a, b, c=4] = [2, 3];//2,3,4
  [a, b, c] = [2, 3];//2,3, undefined
 }

//应用场景
    {
        let a = 1;
        let b = 2;
        [a, b] = [b, a];// 变量交换--传统,需要使用中间变量存储
        console.log(a, b);
      }
     {
        function f(){
          return [1, 2, 3];
        }
        let a, b, c;
        [a, b, c] = f();// 传统需要:先接收,用索引解析
        [a, ...b] = f();//不确定函数返回个数,只关心第一个,后面的用数组存储
      }
// 对象解构赋值
      {
        let o={p:42, q:true};
        let {p, q} = o;// 左右得是对象格式
        console.log(p,q);
      }
      {
        let {a=10, b=5} = {a:3};
        console.log(a, b);// 3, 5
      }
      {
        let metaData = {
          title: 'hello',
          test:[{
            title:'test',
            desc:'kiwi'
          }]
        }// 嵌套
        let {title:esTitls, test:[{title:cnTitle}]} = metaData;
        console.log(esTitls, cnTitle);// hello, test
      }
// 字符串结构赋值
      {
        let [a,b,c,d,e] = 'hello';// 将字符串作为一个类似于数组的值进行解构赋
        console.log(a,b,c,d,e);
        let {length} = 'hello';// 对于属性解构赋值,字符串类似于数组的对象,都有一个length属性
        console.log(length);
      }
// 数值,布尔值先转化为对象
      {
        let {toString:a} = 123;// Number对象
        console.log(a);
        console.log(a === Number.prototype.toString);
        let {toString:b} = true;// Boolean对象
        console.log(b);
        console.log(b === Boolean.prototype.toString);
      }
// 函数参数解构赋值
      {
        function f(x, y){
          return [x,y];
        }
        let  x, y;
        [x, y] = f(x=10, y=12);
        console.log(x, y);// 10, 12
      }
// undefined和null无法转为对象,所以对它们进行解构赋值,都会报错
      {
        let {a} = undefined;
        let {b} = null;
        console.log(a, b); //Cannot destructure property `a` of 'undefined' or 'null'.
      }

你可能感兴趣的:(es6-- let const 解构赋值)