var、let、const 的区别
一、var声明的变量会挂载在window上,而let和const声明的变量不会
javascript">var a = 100;
console.log(a,window.a); // 100 100
let b = 10;
console.log(b,window.b); // 10 undefined
const c = 1;
console.log(c,window.c); // 1 undefined
1
2
3
4
5
6
7
8
二、var声明变量存在变量提升,let和const不存在
javascript">console.log(a); // undefined ==> a 已经声明,还没赋值,默认得到undefined值
var a = 100;
console.log(b); // 报错:b is not defined ==> 找不到 b 这个变量
let b = 10;
console.log(c); // 报错:c is not defined ==> 找不到 c 这个变量
const c = 1;
1
2
3
4
5
6
7
8
三、let和const声明形成块作用域
javascript">if(1){
var a = 100;
let b = 10;
}
console.log(a); // 100
console.log(b) // 报错:b is not defined ===> 找不到 b 这个变量
1
2
3
4
5
6
7
if(1){
var a = 100;
const c = 1;
}
console.log(a); // 100
console.log(c) // 报错:c is not defined ===> 找不到c这个变量
1
2
3
4
5
6
7
四、同一作用域下let和const不能声明同名变量,而var可以
javascript">var a = 100;
console.log(a); // 100
var a = 10;
console.log(a); // 10
1
2
3
4
5
let a = 100;
let a = 10;
// 控制台报错:Identifier 'a' has already been declared ===> 标识符 a 已经被声明了。
1
2
3
4
五、暂存死区
javascript">var a = 100;
if(1){
a = 10;
//在当前块作用域中存在a使用let/const声明的情况下,给a赋值10时,只会在当前作用域找变量a,
// 而这时,还未到声明时候,所以控制台Error:a is not defined
let a = 1;
}
1
2
3
4
5
6
7
8
六、const
/*
* 1、一旦声明必须赋值,不能使用null占位。
*
* 2、声明后不能再修改
*
* 3、如果声明的是复合类型数据,可以修改其属性
*
* */
const a = 100;
const list = [];
list[0] = 10;
console.log(list); // [10]
const obj = {a:100};
obj.name = 'apple';
obj.a = 10000;
console.log(obj); // {a:10000,name:'apple'}
转载自https://www.cnblogs.com/zhaoxiaoying/p/9031890.html
for循环 let和var输出不一样问题
var
javascript"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
</body>
</html>
<script>
const btns=document.getElementsByTagName("button")
for(var i=0;i<5;i++){
btns[i].onclick=function(){
alert(i+1)
}
}
</script>
let
javascript"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
</body>
</html>
<script>
const btns=document.getElementsByTagName("button")
for(let i=0;i<5;i++){
btns[i].onclick=function(){
alert(i+1)
}
}
</script>
因为onclick时一个异步操作 是由当我们点击才执行 而for时同步操作var会使变量提升把for循环执行完之后才会执行onclick事件
也就是var i是一个全局变量 刚开始使i一直加加加 加完之后定时器才进入队列,然后得到一个最终值再btns[i]调用
let就不一样了 let使块级作用域,不会进行变量的提升也就是let把i分成五块 每一块都有onclick
把他包裹再一个函数中中他就不会进行变量提升,因为函数的提升是不会去执行的,每次循环一下就会执行里面的立即执行函数,立即执行函数是没有变量提升的,每次循环一次就会把i传给定时器
图片来自https://juejin.cn/post/7062717676677759013