博客
关于我
var 与 const let的区别
阅读量:192 次
发布时间:2019-02-28

本文共 1326 字,大约阅读时间需要 4 分钟。

一、var 变量可以挂载在window上,而const、let不会挂载的window上。

var a = 100;console.log(a,window.a);    // 100 100let b = 10;console.log(b,window.b);    // 10 undefinedconst c = 1;console.log(c,window.c);    // 1 undefined

二、var有变量提升的概念,而const、let没有变量提升的概念

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;

其实怎么说呢?

三、var没有块级作用域的概念,而const、let有块级作用于的概念

if(1){    var a = 100;    let b = 10;}console.log(a); // 100console.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这个变量

 

四、var没有暂存死区,而const、let有暂存死区

var a = 100;if(1){    a = 10;    //在当前块作用域中存在a使用let/const声明的情况下,给a赋值10时,只会在当前作用域找变量a,    // 而这时,还未到声明时候,所以控制台Error:a is not defined    let a = 1;}

五、let、const不能在同一个作用域下声明同一个名称的变量,而var是可以的

var a = 100;console.log(a); // 100var a = 10;console.log(a); // 10

 

let a = 100;let a = 10;//  控制台报错:Identifier 'a' has already been declared  ===> 标识符a已经被声明了。

六、const相关

当定义const的变量时候,如果值是值变量,我们不能重新赋值;如果值是引用类型的,我们可以改变其属性。

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'}

 

转载地址:http://ygni.baihongyu.com/

你可能感兴趣的文章
mt_rand
查看>>
mysql -存储过程
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>