const关键字
const声明的变量必须直接初始化且不允许二次赋值,如下代码:
<script type="text/javascript">
const name="Tom";
console.log(name);
name="Tim";//报错:TypeError: invalid assignment to const `name'
console.log(name);
</script>
1
2
3
4
5
6
let关键字
和var一样,let也用于声明变量,那么var声明的变量和let声明的变量有何不同:
全局作用域
let声明的变量不会作为全局对象window的属性,而var声明的变量则可以,如下代码:
<script type="text/javascript">
let address="河南省郑州市高新区";
console.log(address);
console.log(window.address);//undefined
</script>
1
2
3
4
5
<script type="text/javascript">
var address="河南省郑州市高新区";
console.log(address);
console.log(window.address);
</script>
1
2
3
4
5
函数作用域
和var一样,都用于声明变量,此时两者没有区别:
<script type="text/javascript">
function print(){
var address="河南省郑州市高新区";
console.log(address);
}
print();
</script>
1
2
3
4
5
6
7
<script type="text/javascript">
function print(){
let address="河南省郑州市高新区";
console.log(address);
}
print(http://www.my516.com);
</script>
1
2
3
4
5
6
7
语句块作用域
let声明的变量只能用于语句块作用域内,而var声明的变量还可以在语句块作用域外使用
<script type="text/javascript">
if(true){
let address="河南省郑州市高新区";
console.log(address);
}
console.log(address);//ReferenceError: address is not defined
</script>
1
2
3
4
5
6
7
<script type="text/javascript">
if(true){
var address="河南省郑州市高新区";
console.log(address);
}
console.log(address);
</script>
1
2
3
4
5
6
7
重复声明
let不能重复声明变量,var则可以
<script type="text/javascript">
let address="河南省郑州市高新区";
let address = "吉林省长春市宽平区";
console.log(address);
</script>
错误信息:
SyntaxError: redeclaration of let address
1
2
3
4
5
6
7
<script type="text/javascript">
var address="河南省郑州市高新区";
var address = "吉林省长春市宽平区";
console.log(address);//输出:吉林省长春市宽平区
</script>
---------------------