for (let i = 0; i < 3; i++) { }; console.log(i);//undefined
for (var i = 0; i < 3; i++) { console.log(i);//0,1,2 }; console.log(i);//3
使用let或者const声明的变量 不能在被重新声明
1 2 3 4 5 6 7
var dad = '我是爸爸!'; console.log(dad); var dad = '我才是爸爸!'; console.log(dad);
let son = '我是儿子'; let son = '我才是儿子';// Identifier 'son' has already been declared
不存在变量提升
1 2 3 4 5
// console.log(dad); // var dad = '我是爸爸!';
// console.log(dad); // let dad = '我是爸爸!';//Identifier 'dad' has already been declared
暂存死区
1 2 3 4 5 6
let a=1 (function(){ console.log(a);//Identifier 'dad' has already been declared //此处往上为死区 let a=2; }())
var 和 let 作用域有效问题
生成十个按钮 每个按点击的时候弹出1 - 10
1 2 3 4 5 6 7 8 9 10 11
var i = 0; for (i = 1; i <= 10; i ++) { (function(i) {//若没有函数自调用则会在最后弹出11,11,11,11 var btn = document.createElement('button'); btn.innerText = i; btn.onclick = function() { alert(i) }; document.body.appendChild(btn); })(i); }
let就可以直接写
1 2 3 4 5 6 7 8
for (let i = 1; i <= 10; i ++) { var btn = document.createElement('button'); btn.innerText = i; btn.onclick = function() { alert(i) }; document.body.appendChild(btn); }