What is the difference between var and let in a for loop?

let homeTravelItemImg = document.getElementsByClassName("item-img");

let homeTravelItemIcon = document.getElementsByClassName("item-icon");

for (var i = 0; i < homeTravelItemIcon.length; iPP) {
    homeTravelItemIcon[i].onclick = function() {
        homeTravelItemImg[i].style.opacity = "1";
        homeTravelItemIcon[i].style.display = "none";
    }
}
The main thing the

code implements is that when I click on an icon, the icon disappears and the opacity of the background image changes;

when I trigger the click event, the console reports an error:

Uncaught TypeError: Cannot read property "style" of undefined

and I will not report an error when I change the var of the for loop to let. Why?

is it because of the block-level scope?

Es6
Mar.04,2021

look here https://codeshelper.com/a/11.


you can make a breakpoint to know that in onclick, when you execute it, the value of I should be homeTravelItemIcon.length.
cannot find the relevant DOM node, so it reports an error.

use this directly in it

let homeTravelItemImg = document.getElementsByClassName("item-img");

let homeTravelItemIcon = document.getElementsByClassName("item-icon");

for (var i = 0; i < homeTravelItemIcon.length; iPP) {
    homeTravelItemIcon[i].onclick = function() {
        this.style.opacity = '1';
        this.style.display = 'none';
    }
}

/ / is mainly defined by var inside the non-method, which is equivalent to global and can be accessed anywhere. When the browser engine parses, it will not
open a local variable internally, but directly reference the address of the external variable.

/ / the way you use let should be consistent with the following.

for (var i = 0; i < homeTravelItemIcon.length; iPP) {
  
    (function(i){homeTravelItemIcon[i].onclick = function() {
        homeTravelItemImg[i].style.opacity = '1';
        homeTravelItemIcon[i].style.display = 'none';
    }})(i);
}

variable promotes
scope


1.var causes variable escalation. If you var I in the for loop, then you can find the
of I in this scope, such as for (var i = 0bot I < 5x IPP) {}
console.log (i) / / 5

.

2.let is declared in Es6, but the declared variables are only valid within the block of code where the let command is located. For more information, please see http://es6.ruanyifeng.com/-sharpdo.

for more information on
for (let i = 0 href= I < 5 scape IPP) {}
console.log (i) / / error reporting
.
Menu