1、 let的声明:
1
2
3
4
5
6
7
8
9<body> <script> //1、变量的声明 let a ; let b,c,d; let e=10; let f=495,g='whdi',h=[]; </script> </body>
2、let变量不能重复声明,var可以
1
2
3
4
5
6
7
8<body> <script> //2、变量不能重复声明 let i = 0; let i = 'sdhd'; </script> </body>
Uncaught SyntaxError: Identifier 'i' has already been declared-------let变量不能重复声明
3、在ES5中有3种作用域:全局、函数、eval(ES5的严格模式),ES6-let-块级作用域-let 是在代码块内有效
1
2
3
4
5
6
7
8
9<body> <script> //3、代码块内有效 { let boy='ddh' } console.log(boy) </script> </body>
Uncaught ReferenceError: girl is not defined at let.html:14:15————let块级作用域--不单指花括号--还有while if else for 循环语句也是块级作用域
var没有块级作用域--在全局的window上读取
4、let 不存在变量提升,var 会变量提升————
1
2
3
4
5
6
7<body> <script> //4、let 不存在变量提升,var 会变量提升 console.log(a) var a='f' </script> </body>
var相当于会在前面声明 var a ,var当脚本开始运行的时候,a已经存在了,但是还没有赋值
1
2
3
4
5
6
7<body> <script> //4、let 不存在变量提升,var 会变量提升 console.log(a) let a='f' </script> </body>
Uncaught ReferenceError: Cannot access 'a' before initialization
5、let 不影响作用链效果
1
2
3
4
5
6
7
8
9
10
11
12<body> <script> //5、let 不影响作用链效果 { let a='你好' function C(){//函数也是一个作用域 console.log(a)//函数作用域没有a变量 会像向上一级寻找 } C() } </script> </body>
let实现:点击切换颜色_this实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>let</title> <style type="text/css"> .item{ border: 1px solid #1bb3d2; width: 100px; height: 100px; float: left; margin: 10px; } </style> </head> <body> <div class="container"> <h2 class="page-header">点击切换颜色</h2> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <script> var items=document.getElementsByClassName('item'); for(var i=0;i<items.length;i++){//块级作用域---var是全局变量 items[i].onclick=function(){ this.style.background='pink'; } } </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22//var全局变量 直接var=2 只执行一次 {var i=0 items[i].onclick=function(){ items[i].style.background='pink' } } {var i=1 items[i].onclick=function(){ items[i].style.background='pink' } } {var i=2 items[i].onclick=function(){ items[i].style.background='pink' } }
Uncaught TypeError: Cannot read properties of undefined (reading 'style') --var属性是全局--已经是i=3其中的item[i]会不存在,let块级作用域,i 只在本轮循环中有效,每次循环的 i其实都是一个新的变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21{let i=0 items[i].onclick=function(){ items[i].style.background='pink' } } {let i=1 items[i].onclick=function(){ items[i].style.background='pink' } } {let i=2 items[i].onclick=function(){ items[i].style.background='pink' } }
1
2
3
4
5
6
7
8
9
10
11<script> let items=document.getElementsByClassName('item'); for(let i=0;i<items.length;i++){//块级作用域---var是全局变量 items[i].onclick=function(){ items[i].style.background='pink' } } </script>
最后
以上就是勤奋铅笔最近收集整理的关于ECMAScrip-ES6-新变量-let--注意块级作用域的全部内容,更多相关ECMAScrip-ES6-新变量-let--注意块级作用域内容请搜索靠谱客的其他文章。
发表评论 取消回复