当前位置:网站首页>ES6简介及let、var、const区别
ES6简介及let、var、const区别
2022-08-03 20:04:00 【嘿………】
ECMAScript6
一、简介
1、什么是ES6?
- ES的全称是ECMAScript,它是由ECMA国际标准化组织,制定的一项脚本语言的标准化规范。
2、为什么使用ES6?
- 变量提升特性增加了程序运行时的不可预测性
- 语法过于松散,实现相同的功能,不同的人可能会写出不同的代码
二、let(ES6新增的用于声明变量的关键字)
(1)let声明的变量只在所处于的块级有效
//let关键字就是用来声明变量的
let a = 10;
console.log(a); //10
//使用let关键字声明的变量具有块级作用域
if(true){
let b = 10;
console.log(b); //10
}
console.log(b); //报错:b is not defined
//在一个大括号中使用let关键字声明的变量才具有块级作用域,var关键字是不具备这个特点的
if(true){
let a = 10;
var b = 20;
}
console.log(b); //20
console.log(a); //报错:a is not defined
//防止循环变量变成全局变量
for(var i = 0; i < 2; i++){ //使用var
}
console.log(i); //2
for(let i = 0; i < 2; i++){ //使用let
}
console.log(i); //报错:i is not defined
(2)不存在变量提升
//使用let关键字声明的变量没有变量提升
console.log(a); //报错:a is not defined
let a = 20;
(3)暂时性死区
//使用let关键字声明的变量暂时性死区
var num = 123;
if(true){
console.log(num); //报错:num is not defined
let num = 12;
}
三、 const(ES6新增的关键字)
作用:声明常量,常量就是值(内存地址)不能变化的量。
(1)具有块级作用域
//使用const关键字声明的常量具有块级作用域
if(true){
const a = 10;
console.log(a); //10
}
console.log(a); //a is not defined
(2)声明常量时必须赋值
//使用const关键字声明的常量必须赋初始值
const PI; //报错: Missing initializer in const declaration
const PI = 3.14;
(3)常量赋值后,值不能修改
//常量声明后值不可更改
const PI = 3.1415;
PI = 100; //报错:Assignment to constant variable 不能更改常量的值
const arr = [100,200];
arr[0] = "a";
arr[1] = "b";
console.log(arr); //['a','b']
arr = ['a','b']; //报错:Assignment to constant variable
四、let、const、var的区别
使用var声明的变量,其作用域为该语句所在的函数内,且存在变量提升现象。
使用let声明的变量,其作用域为该语句所在的代码块内,不存在变量提升。
使用const声明变量的是常量,在后面出现的代码中不能再修改该常量的值。
边栏推荐
- MySQL Basics
- 子树的大小
- Detailed steps for tensorflow-gpu2.4.1 installation and configuration
- 【微信小程序2】事件传参与数据同步[03]
- Benchmarking Lane-changing Decision-making for Deep Reinforcement Learning
- CLIP论文解读
- redis常用命令,HSET,XADD,XREAD,DEL等
- RNA核糖核酸修饰Alexa 568/[email protected] 594/[email prote
- In-depth understanding of JVM-memory structure
- Pytorch GPU 训练环境搭建
猜你喜欢

ThreadLocal详解
Teach you to locate online MySQL slow query problem hand by hand, package teaching package meeting

虚拟机vmware设置桥接模式上网

单调栈及其应用

ESP8266-Arduino编程实例-WS2812驱动

简易电子琴设计(c语言)

Interview Blitz: What Are Sticky Packs and Half Packs?How to deal with it?

List类的超详细解析!(超2w+字)

涨薪5K必学高并发核心编程,限流原理与实战,分布式计数器限流

告诉你0基础怎么学好游戏建模?
随机推荐
一种能有效缓解环境噪声对音频质量干扰的方案
从腾讯阿里等大厂出来创业搞 Web3、元宇宙的人在搞什么
Node version switching tool NVM and npm source manager nrm
转运RNA(tRNA)甲基化修饰7-甲基胞嘧啶(m7C)|tRNA-m7G
调用EasyCVR接口时视频流请求出现404,并报错SSL Error,是什么原因?
危化企业双重预防机制数字化建设进入全面实施阶段
ESP8266-Arduino编程实例-MCP4725数模转换器驱动
那些年我写过的语言
WPF .cs中使用资源文件中的ControlTemplate或Style并找到控件
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
Anaconda 虚拟环境迁移
Redis 内存满了怎么办?这样置才正确!
算法--交错字符串(Kotlin)
C中的数据存储
头条服务端一面经典10道面试题解析
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
调用EasyCVR云台控制接口时,因网络延迟导致云台操作异常该如何解决?
染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
php截取中文字符串实例
2022 年值得尝试的 7 个 MQTT 客户端工具