当前位置:网站首页>ES6 introduction and let, var, const
ES6 introduction and let, var, const
2022-08-03 20:14:00 【Hey………】
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)暂时性死区
//使用letThe keyword declare variables of temporary dead zone
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声明的变量,其作用域为该语句所在的代码块内,不存在变量提升.
使用constDeclare variables is constant,在后面出现的代码中不能再修改该常量的值.
边栏推荐
猜你喜欢
随机推荐
LeetCode 899. 有序队列
信使mRNA甲基化偶联3-甲基胞嘧啶(m3C)|mRNA-m3C
Node version switching tool NVM and npm source manager nrm
Go语言为任意类型添加方法
PHP according to the longitude and latitude calculated distance two points
LeetCode 1374. 生成每种字符都是奇数个的字符串
盲埋孔PCB叠孔设计的利与弊
ES6解构赋值--数组解构及对象解构
百利药业IPO过会:扣非后年亏1.5亿 奥博资本是股东
面试官:为什么 0.1 + 0.2 == 0.300000004?
leetcode 1837. The sum of the digits in the K-base representation
Edge box + time series database, technology selection behind Midea's digital platform iBuilding
622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
安装anaconda并创建虚拟环境
Pytorch GPU 训练环境搭建
Auto.js脚本程序打包
Hinton2022年RobotBrains访谈记录
【飞控开发高级教程3】疯壳·开源编队无人机-定高、定点、悬停
Why BI software can't handle correlation analysis
数据驱动的软件智能化开发| ChinaOSC









