01 let和const
let和const的共同点:
1.声明的变量不会有变量提升
2.是一个块作用域的
3.不允许重复声明
let和const的作用:
1.for循环是一个经典的例子。
2.不会影响全局污染
const的特殊性:一旦被声名,无法被修改。
下面通过代码展示let和const的各种特点:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>01 let和const</title>
</head>
<body>
</body>
<script>
// let和const
// 1.let 它跟var一样都是来声明变量,但是有所不同
// var声明的变量会有变量提升
// console.log(a);
// var a = 2;
// let声明的变量不会有变量提升,是一个块作用域的
// console.log(a);
// let a = 2;
if(1===1){
let b = 10;
}
console.log(b);
// 不允许重复声明
// let c = 10;
// let c = 30;
// console.log(c);
// const声明的变量会被认为是常用,一旦被赋值以后 无法改变。所以const声明变量时立马赋值
// const max = 30;
// max = 40;
// const min;
// const声明的变量也属于块级作用域的
// if(2===2){
// const name = 'mjj';
// }
// console.log(name);
/* const person = {
name:'mjj'
}
// 可以修改变量成员
person.name = 'alex';
console.log(person); */
// 暂时性死区
// if(1===1){
// console.log(a);
// let a = 10;
// }
// for循环是一个经典的例子。
var arr = []
for(let i = 0; i < 10; i++){
// arr[i] = (function(n) {
// return function () {
// return n;
// }
// })(i);
arr[i] = function () {
return i;
}
}
console.log(arr[5]());
// 使用let声明的变量不会影响全局污染
// console.log(RegExp);
let RegExp = 10;
console.log(RegExp);
console.log(window.RegExp);
// 关于let和const在以后的开发中最佳应用:
// 在默认情况下用const,而只有你在知道变量值需要被修改的情况下使用let
//let和const的共同点:
//1.声明的变量不会有变量提升
//2.是一个块作用域的
//3.不允许重复声明
//let和const的作用:
//1.for循环是一个经典的例子。
//2.不会影响全局污染
//const的特殊性:一旦被声名,无法被修改。
</script>
</html>