<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//let: 声明变量 / 只在所在代码块(块级作用域)内有效
//const: 声明常量 / 不可更改
let a1 = 10
const PI = 3.1415
//块级作用域 : 提前声明仅限当前所在块内
//例 :
// fn() //es6语法.html:21 Uncaught TypeError: fn is not a function /at es6语法.html:21
{
//这是一个块级作用域
fn() // 1 /es6语法.html:26
function fn() {
console.log(1);
}
}
fn() // 1 /es6语法.html:26
//例 : let 与 var 的区别
//let 声明的变量不能被前声明
{
var a2 = 10
console.log(a2); //es6语法.html:39 /10
}
console.log(a2); //es6语法.html:41 /10
{
// console.log(b2); //不能被提前声明 /*es6语法.html:43 Uncaught ReferenceError: Cannot access 'b2' before initialization at es6语法.html:43*/
let b2 = 20
console.log(b2); /*es6语法.html:44 20*/
}
//console.log(b2); /* es6语法.html:46 Uncaught ReferenceError: b2 is not defined.at es6语法.html:46*/
//const 声明的常量无法被提前声明
//const 声明的常量无法修改
{
//console.log(a3);
const a3 = 20
//a3 = 21 //es6语法.html:55 Uncaught TypeError: Assignment to constant variable.at es6语法.html:55
}
//let 声明的变量名称不能重复
{
let a4 = 10
/* let a4 = 20 //Uncaught SyntaxError: Identifier 'a4' has already been declared */
}
{
for (var i = 0; i < 10; i++) {
setTimeout(() => {
console.log(i); //输出10个10
}, 0);
}
for (let j = 0; j < 10; j++) {
console.log(j); // 0 1 2 3 4 5 6 7 8 9
}
}
//暂时性死区
{
var a5 = 20
{
//console.log(a5); //es6语法.html:78 Uncaught ReferenceError: Cannot access 'a5' before initialization
let a5 = 10
console.log(a5); // 10
}
console.log(a5); // 20
}
</script>
</body>
</html>