当前位置:网站首页>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声明变量的是常量,在后面出现的代码中不能再修改该常量的值。
边栏推荐
猜你喜欢

嵌入式分享合集27

入门3D建模基础教程详细分解
Teach you to locate online MySQL slow query problem hand by hand, package teaching package meeting

622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)

NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)

Pytorch GPU 训练环境搭建

从文本匹配到语义相关——新闻相似度计算的一般思路

149. 直线上最多的点数-并查集做法

Network protocol-TCP, UDP difference and TCP three-way handshake, four wave

xss.haozi练习通关详解
随机推荐
安装anaconda并创建虚拟环境
2022 年值得尝试的 7 个 MQTT 客户端工具
自定义form表单验证
149. The largest number on a straight line, and check the set
Redis 内存满了怎么办?这样置才正确!
Reveal how the five operational management level of hundreds of millions of easily flow system
子结点的数量(2)
WPF .cs中使用资源文件中的ControlTemplate或Style并找到控件
Edge box + time series database, technology selection behind Midea's digital platform iBuilding
危化企业双重预防机制数字化建设进入全面实施阶段
xss.haozi练习通关详解
8.2模拟赛总结
YARN功能介绍、交互流程及调度策略
后台图库上传功能
那些年我写过的语言
花 30 美金请 AI 画家弄了个 logo,网友:画得非常好,下次别画了!
dpkg强制安装软件
友宏医疗与Actxa签署Pre-M Diabetes TM 战略合作协议
RNA核糖核酸修饰Alexa 568/[email protected] 594/[email prote
Auto.js脚本程序打包