zoukankan      html  css  js  c++  java
  • ECMAScript 6中的var,let,const

    var的变量提升

    console.log(a);  //输出undefined
    var a=10;
    
    他的实际执行顺序是:
    
    var a;
    console.log(a);
    a=10
    
    这就是var的变量提升

    const命令的用法

    const声明的是一个只读的常量,一旦声明,就不可改变.

    const a=3.14  //声明的常量a不可更改
    //a=123   因为它声明的常量不可更改,所以这句会报错  // TypeError: Assignment to constant variable.
    console.log(a)

    const声明的常量只在块级有效

    if(true){
            const who="wxp"
        }
    console.log(who) //who is not defined

    const声明的常量不存在变量的提升

    console.log(a);//a is not defined
    const a=3.14

    const不可重复声明常量

    var msg="hello";
    const msg="world" //Identifier 'msg' has already been declared

    const实际上保证的,并不是变量的值不得改动,而是变量指向的那个内存地址不得改动。对于简单类型的数据(数值、字符串、布尔值),值就保存在变量指向的那个内存地址,因此等同于常量。但对于复合类型的数据(主要是对象和数组),变量指向的内存地址,保存的只是一个指针,const只能保证这个指针是固定的,至于它指向的数据结构是不是可变的,就完全不能控制了。

    const arr=[]  //声明的数组保存的是指针,所以无法保证它里面的值是固定的。
    const obj={}  //跟数组一样都是 可变数据类型
    arr.push(123)
    obj.name="wxp"
    
    console.log(arr)  //[123]
    console.log(obj)  //{name:"wxp"}

    如果真的想将对象冻结,应该使用Object.freeze方法。

     const foo=Object.freeze({});  //foo指向的是一个冻结对象,所以无法对它添加新的属性。
    foo.age=22   //不生效,因为foo是一个冻结对象。严格模式时还会报错
    console.log(foo) //{}

    let命令的用法

    let是 JavaScript 新增了块级作用域。跟const一样,只对块级有效

       let a=10
       if(true){
            let a=5
            console.log(a) //5
        }
        console.log(a) //10

    let跟const一样不可重复声明

    var a=10
    let a=20  //Identifier 'a' has already been declared
  • 相关阅读:
    服务限流原理及算法
    Kafka 与 RabbitMQ 如何选择使用哪个?
    分布式事务之最终一致性实现方案
    如何在Ubuntu 14.04中使用systemctl?
    postgresql13 for window 安装及备份还原数据
    手把手教大家在mac上用VMWare虚拟机装Ubuntu
    在Mac平台上使用Multipass安装Ubuntu虚拟机
    如何在markdown中插入js和css
    HTML5标签
    linux
  • 原文地址:https://www.cnblogs.com/wxp5257/p/8361726.html
Copyright © 2011-2022 走看看