变量声明
var、let、const
作用域:变量的作用范围
- 全局 - 非函数
- 函数 - 函数包含
- 块作用域 -一对{}包含的范围
var
- 支持变量声明预解析
- 不支持块作用域
- 允许重复声明
let
- 不支持变量声明预解析(先声明后使用)
- 支持块作用域
- 不允许重复声明(暂存死区)
const
- 不支持变量声明预解析(先声明后使用)
- 支持块作用域
- 不允许重复声明(暂存死区)
- 常量(值一旦确定,不允许修改,所以必须初始化)
例子:
{
var a = 1;
let b = 2;
const c = 3;
}
console.log(a);
console.log(b);
console.log(c);
结果为:
1
Uncaught ReferenceError: b is not defined
Uncaught ReferenceError: c is not defined
故let和const在块作用域外是无法引用的
html的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
button.active {
background: yellow;
}
p {
display: none;
}
p.active {
display: block;
}
</style>
</head>
<body>
<button class="active">选项一</button>
<button>选项二</button>
<button>选项三</button>
<p>内容一</p>
<p>内容二</p>
<P>内容三</P>
</body>
<script>
var buttons = document.querySelectorAll('button');
var ps = document.querySelectorAll('p');
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
for (let i = 0; i < buttons.length; i++) {
buttons[i].className = '';
ps[i].className = '';
}
this.className = 'active';
ps[i].className = 'active';
}
}
</script>
</html>
效果: