当前位置:网站首页>ES6--let与const
ES6--let与const
2022-07-13 17:36:00 【爱喝珍珠奶茶】
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
1.代码块
代码块是没有作用域的
var obj={name:"karen"}; //对象
var fn=function( ){ } //函数
{ } if( ){ } for( ){ } // 代码块
案例1:{ } 没有作用域
label1:{
var a=20;
var b=30
console.log(a)
}
console.log(b)运行结果:

只有函数才有作用域
案例2:if( ){ }没有作用域
if([]){
var a=20;
console.log(a);
}
console.log(a);
运行结果:

案例3: for( ){ } 没有作用域
var arr=[]
for(var i=0;i<10;i++){
// console.log(i)
function fn(){console.log(i)}
arr.push(fn)
}
arr[0]()
运行结果:

2.let与const
let 声明的变量只在 let 命令所在的代码块内有效(块级作用域、局部作用),ES6 推荐在函数中使用 let 定义变量,而非 var。
const 声明一个只读的常量,一旦声明,常量的值就不能改变。
3.ES6新的变量修饰符
(1)声明不赋值 先访问在声明 声明相同的变量名
console.log(a)
var a=0;
运行结果:

(2)let 也可以声明不赋值 不能先访问在声明 不能声明相同的变量名

(3)块级作用域
案例1:
{
let a=100;
console.log(a,1111)
a="hello"
console.log(a,222)
}
console.log(a,333)运行结果:

(4)笔试题
案例1:
let a=90
console.log(a)
if(true){
console.log(a)
var a=20
}
console.log(a)运行结果:

4.const与let的不同
const js的常量修饰符,一旦声明,常量的值就不能改变
let var 修饰的变量的值可以被修改
例如:
const url="http://www.hqyj.com"
url=200
其他语法同let, 只能初始化一次
初始化定义:第一次赋值
例如:
var a=20//初始化
a=90
var b;
b=20;//初始化
b=90;
注意要点:
let 和const 关键词声明的变量不具备变量提升(hoisting)特性
let 和 const 声明只在最靠近的一个块中(花括号内)有效
当使用常量 const 声明时,请使用大写变量,如:CAPITAL_CASING
const 在声明时必须被赋值
const 如何做到变量在声明初始化之后不允许改变的?使用 const 声明复杂类型对象时要慎重。
边栏推荐
- Dynamic programming leetcode509 Fibonacci number
- MVN clean or MVN clean package did not detect the test file
- 抓包工具之fiddler的安装使用
- 【Tensorflow2】AttributeError: ‘Tensor‘ object has no attribute ‘numpy‘ 解决 (tf.py_function)
- 数据操作—查询篇
- ES6新增的class类
- The 13th provincial competition of Bluebridge cup single chip microcomputer
- 对象成员检测
- ES6--箭头函数
- JS数组的内置功能
猜你喜欢

Is the sub database and sub table really suitable for your system? Talk about how to select sub databases, sub tables and newsql

解决IDEA2020连接MySQL8出现unable to load authentication plugin ‘caching_sha2_password‘异常

Idea自动导出数据库中表的sql语句

21天SQL打卡总结

一文理解分布式开发中的服务治理

Jmeter相关知识整理

流批一体在京东的探索与实践

Practice of Flink CDC in Dajian cloud warehouse

Design and implementation of an eight bit compensator based on logisim

蓝桥杯单片机第13届省赛题
随机推荐
几种经典功率谱密度估计方法的记录(从滤波的视角出发)
遍历器总结
yandex bot user agent
P1664 clock in every day and feel good [getting started]
Design and implementation of an eight bit compensator based on logisim
Le 13ème concours provincial de Blue Bridge Cup MCU
JS中的JSON(推出对象深拷贝)
非功能方面测试
Implementation of drop-down box function in SSM project
ES6的高级赋值方法——解构赋值
Installation and use of fiddler in packet capturing tool
Aunt Qian's real-time risk control practice based on Flink
Lu te software Qi Jun: cloud native helps SaaS business tenants to isolate efficiently
渗透测试之靶场安装与攻击机配置
41.js--闭包
Solve the problem that the pictures uploaded by the SSM project cannot be echoed in time
"Cheating" big factories: seven product development strategies that can be referred to
Array changes, but the view cannot be updated (reason and thinking)
C语言:结构体中链表的添加与删除
sql_ Server2014 download and installation