let 和 var 的区别
1、作用域只局限于当前代码块
if(true){
var str = 1
let str1 = 2
console.log(str)
console.log(str1)
}
console.log(str)
console.log(str1)// str1 is not defined
2、let声明的作用于不会被提升
console.log(str)
var str = 1
console.log(str1) // str1 is not defined
let str1 = 2
3、同一作用域下不能定义相同的变量
var str = 1
var str = 11
console.log(str)//覆盖上一个定义的变量
let str1 = 2
let str1 = 22
console.log(str1)//'str1' has already been declared
4、for循环体现let的父子作用域
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
window.onload = function () {
var btns = document.querySelectorAll("button")
for(var i = 0; i<btns.length; i++){
btns[i].onclick= function(){
console.log('第'+i+'个按钮');
}
}
/*解决方法1
var btns = document.querySelectorAll("button")
for (var i = 0; i < btns.length; i++) {
(function (i) {
btns[i].onclick = function () {
console.log('第' + i + '个按钮');
}
})(i)
}*/
/*解决方法2
let btns = document.querySelectorAll("button")
for(let i = 0; i<btns.length; i++){
btns[i].onclick= function(){
console.log('第'+i+'个按钮');
}
}*/
}
</script>
</body>