ES6专题——varletconst的区别和使用场景

Posted sanyi2019

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES6专题——varletconst的区别和使用场景相关的知识,希望对你有一定的参考价值。

  在ES6中,新出了let和const这两个新的声明变量的命令。与之前的var相比,let和const有几个不同的特性。

 

var

  1. 可以重复声明,且存在变量提升
  2. 没有块级作用域
        <!--可以重复声明-->
        var a = "this is a";
        var a = "this is another a";    //重复声明了a
        console.log(a);                 //输出this is another a

        <!--存在变量提升-->
        console.log(b);     //变量提升,var b 被提升至所在作用域顶部,输出undefined
        var b = "this is b";

        <!--无法限制修改-->
        var c = "this is c";
        c = "this is cc";
        c = "this is ccc";
        console.log(c);  //输出this is ccc

        <!--没有块级作用域-->
        {
            var d = "this is d";
            console.log(d); //输出this is d
        }
        console.log(d);     //输出this is d

 

let

1.不能重复声明,且不存在变量提升

2.块级作用域

        <!--不能重复声明-->
        let a = "this is a";
        let a = "this is another a";
        //这里会报错:Uncaught SyntaxError: Identifier ‘a‘ has already been declared

        <!--没有变量提升-->
        console.log(b);
        let b = "this is b";
        //这里会报错:Uncaught ReferenceError: b is not defined

        <!--块级作用域-->
        {
            let c = "this is c";
            console.log(c);     //输出this is c
        }
        console.log(c);
        //这里会报错:Uncaught ReferenceError: c is not defined

 

const

const包含let的所有特性,区别是声明的变量不可以修改(const保证变量指向的内存不可改动,而不是声明的值不能改动

 

        <!--不能更改值-->
        const a = "this is a";
        a = "b";
        console.log(a);
        //这里报错:Uncaught TypeError: Assignment to constant variable.

 

 

 

以上是关于ES6专题——varletconst的区别和使用场景的主要内容,如果未能解决你的问题,请参考以下文章

JS --- varletconst三者的区别

varletconst的区别,已经作用范围。

varletconst的区别

varletconst的区别

varletconst的区别

varletconst的区别