标签:erro 更改 声明 UNC fine not red es6 div
在ES6中,新出了let和const这两个新的声明变量的命令。与之前的var相比,let和const有几个不同的特性。
var
<!--可以重复声明--> 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专题】——var、let、const的区别和使用场景
标签:erro 更改 声明 UNC fine not red es6 div
原文地址:https://www.cnblogs.com/sanyi2019/p/10357518.html