Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Why use a let in sequence?


May 30, 2021 Article blog



Why is it that for loops are used in ES5 using var and let in ES6, and we recommend let?
Because var is a flaw in the design of the js language designer Brendan Eich, this defect cannot be changed, and the author proposed to fix it ten years ago.
In the js language, small partners need to know that in the js language, if and for are not scoped, only function has, var is a global variable, let is a block-level scope, const is a constant (unchangeable variables are called constants); You can make the let look more perfect var

//ES5中使用for循环点击事件 //bug:每次点击都是最后一个点击按钮触发点击
for(var i=0;i<btns.length;i++){
btns[i].addEventListener('click',function(i){
console.log(`第${i}按钮发生点击`);
})
}
//es5中for循环使用var定义的,就相当于定义了一个全局的i,每次循环i++都可以进行改变i的值,
//var进行变量提升和代码预解析后var是在全局最前面的,es5的解决方案是采用闭包进行解决;
//解决方案
for(var i=0;i<btns.length;i++){

( function(num){
btns[i].addEventListener('click',function(i){
console.log(`第${num}按钮发生点击`);
})
})(i);
}
//函数具有块级作用域,把当前每次循环的i通过闭包的方式传递给点击事件,因为是立即执行函数,所以每次传递进去执行
//后,在开始下一轮循环,直到最后点击事件循环完毕,虽然是使用var定义的i,但是i在改变前点击事件通过闭包的方式
//传递进去并执行,直接把当前的i定义在当前函数作用域内

ES6 loop

for(let i=0;i<btns.length;i++){
btns[i].addEventListener('click',function(i){
console.log(`第${num}按钮发生点击`);
})
}
//let具有块级作用域的,每次循环时进去不会改变当前传递i的值,因为每次循环都是变量提升和代码预解析
//都是把let提升到当前作用域的最前方