javascript中var与let、const的区别详解
作者:YINGYAN 时间:2024-05-09 15:07:32
一、var声明的变量会挂载在window上,而let和const声明的变量不会:
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
二、var声明变量存在变量提升,let和const不存在变量提升
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 = 10;
三、let和const声明形成块作用域
if(1){
var a = 100;
let b = 10;
}
console.log(a); // 100
console.log(b) // 报错:b is not defined ===> 找不到b这个变量
if(1){
var a = 100;
const c = 1;
}
console.log(a); // 100
console.log(c) // 报错:c is not defined ===> 找不到c这个变量
四、同一作用域下let和const不能声明同名变量,而var可以
var a = 100;
console.log(a); // 100
var a = 10;
console.log(a); // 10
let a = 100;
let a = 10;
// 控制台报错:Identifier 'a' has already been declared ===> 标识符a已经被声明了。
五、暂存死区
var a = 100;
if(1){
a = 10;
//在当前块作用域中存在a使用let/const声明的情况下,给a赋值10时,只会在当前作用域找变量a,
// 而这时,还未到声明时候,所以控制台Error:a is not defined
let a = 1;
}
六、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
标签:javascript,var,let,const
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL中关于临时表的一些基本使用方法
2024-01-18 01:22:34
matplotlib绘制两点间连线的几种方法实现
2021-07-27 09:02:24
![](https://img.aspxhome.com/file/2023/0/107240_0s.jpg)
Vue 实现穿梭框功能的详细代码
2024-05-09 10:51:53
![](https://img.aspxhome.com/file/2023/8/126588_0s.gif)
python读取并显示图片的三种方法(opencv、matplotlib、PIL库)
2023-03-24 19:43:02
![](https://img.aspxhome.com/file/2023/9/81529_0s.jpg)
使用python+whoosh实现全文检索
2021-01-04 05:29:46
Python配置文件解析模块ConfigParser使用实例
2023-10-19 09:10:19
YUV转为jpg图像的实现
2021-07-26 09:18:29
Django通过自定义认证后端实现多种登录方式验证
2022-09-21 20:15:40
SQL Server 2000安装故障
2008-01-22 19:10:00
Python远程视频监控程序的实例代码
2021-02-08 14:26:22
Pytorch教程内置模型源码实现
2022-09-04 12:58:50
![](https://img.aspxhome.com/file/2023/5/115225_0s.jpg)
PythonPC客户端自动化实现原理(pywinauto)
2022-11-27 02:24:27
![](https://img.aspxhome.com/file/2023/3/95673_0s.png)
IIS6.0下ASP的新增功能
2007-08-22 14:55:00
JavaScript使用正则表达式获取全部分组内容的方法示例
2023-08-27 13:38:18
![](https://img.aspxhome.com/file/2023/4/56214_0s.png)
python如何把嵌套列表转变成普通列表
2023-08-20 14:28:19
如何查看MySQL连接的root密码
2024-01-25 08:47:43
![](https://img.aspxhome.com/file/2023/0/74780_0s.png)
Python3.7中安装openCV库的方法
2021-07-07 04:23:32
python3 wechatpy微信支付的项目实践
2023-08-29 14:13:36
![](https://img.aspxhome.com/file/2023/5/87975_0s.jpg)
python安装pil库方法及代码
2021-10-22 16:55:24
![](https://img.aspxhome.com/file/2023/6/133356_0s.png)
了解WEB页面工具语言XML(五)好处
2008-09-05 17:19:00