2.ES6 let关键字

 

let

let 关键字用来声明变量

1
2
3
4
5
let a;
let b,c,d;
let e = 100;
// 可以一次定义多个变量
let f = 521, g = 'hello', h = [];

使用 let 声明的变量有几个特点:

  1. 不允许重复声明
1
2
3
4
// 1. 变量不能重复声明
let name = 'xiaoming';
let name = 'xiaoli';
// Uncaught SyntaxError: Identifier 'name' has already been declared
1
2
3
var name = 'xiaoming';
var name = 'xiaoli';
// var允许重复定义
  1. 块儿级作用域
1
2
3
4
5
6
// 2. 块儿级作用域: if else while for 
{
let girl = 'Jenny';
}
console.log(girl);
// Uncaught ReferenceError: girl is not defined
1
2
3
4
5
{
var girl = 'Jenny';
}
console.log(girl);
// Jenny
  1. 不存在变量提升
1
2
3
4
5
// 3. 不存在变量提升
// let定义的变量必须先定义后使用
console.log(song);
let song = '恋爱达人';
// Uncaught ReferenceError: Cannot access 'song' before initialization
1
2
3
console.log(song);
var song = '恋爱达人';
// undefined
  1. 不影响作用域链
1
2
3
4
5
6
7
8
9
// 4. 不影响作用域链
{
let school = 'CMU';
function fn(){
console.log(school);
// CMU
}
fn();
}

案例:实现点击改变背景颜色

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
37
38
39
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>点击 DIV 换色</title>
<link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<style>
.item {
width: 100px;
height: 50px;
border: solid 1px rgb(42, 156, 156);
float: left;
margin-right: 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>
let items = document.getElementsByClassName("item");
for (let i = 0; i < items.length; i++) {
items[i].onclick = function() {
items[i].style.background = "pink";
};

}
</script>
</body>

</html>