let关键字

时间:2021-02-10 17:36:13
作用:
与var类似, 用于声明一个变量
特点:
只在块作用域内有效
不能重复声明
不会预处理, 不存在提升
应用:
循环遍历加监听 //应用实例
<body>
<button>测试1</button><br>
<button>测试2</button><br>
<button>测试3</button><br>
</body>
console.log(a); //undefined   (变量/函数)提升
//不会预处理, 不存在提升
//console.log(b); //Uncaught ReferenceError: b is not defined var a = 2;
let b = 3;
console.log(a, b); if(true) {
var c = 4;
let d = 5;
var c = 6;
//不能重复声明
//let d = 7; //Uncaught SyntaxError: Identifier 'd' has already been declared
console.log(c, d);
}
console.log(c);
//只在块作用域内有效
//console.log(d); //Uncaught ReferenceError: d is not defined //循环遍历加监听
var buttons = document.getElementsByTagName("button");
for (let i = 0,length=buttons.length; i<length; i++) {
buttons[i].onclick = function () {
alert('点击'+(i+1)+'个按钮');
};
}