var and let variables for traversal issue

document.getElementsByTagName Liarry = var ( 'Li'); 

/ *
* a method
* Description: Since the function is executed when the variable parameter into (Thought closure, save the current value).
* /

For (var I = 0; I <Liarry.length; I ++) {
(function (J) {
Liarry [J] .addEventListener ( 'the Click', function () {
the console.log (J);
})}) (I);
}


/ *
* method II
* description: the variable value stored in the current li object.
* /

For (var I = 0; I <Liarry.length; I ++) {
Liarry [I] = I .index
Liarry [I] .addEventListener ( 'the Click', function () {
the console.log (this.index)
} )
}


/ *
* method three
* description: defines a function of time, pass arguments (essentially a global variable becomes a local variable)
* /

for (var I = 0; I <Liarry.length; I ++) {
ClickEvent (I);
}

function ClickEvent (J) {
Liarry [J] .addEventListener ( 'the Click', function () {
the console.log (J);
})
}


/ *
* Method IV
* declare variables using let
* /

for (the let I = 0; I <Liarry.length; I ++) {
Liarry [I] .addEventListener ( 'the Click', function () {
the console.log (I);
});
}


* forth (understand, there are deficiencies comments welcome a wave of local area to go):
1, there is a variable var declared variable lift, var statement is a global variable. When js engine to execute a for loop, each li will add a click event, this time did not trigger this event, click callback did not execute, the callback i did not assign, terminate the loop until i equal length, when trigger click, the callback is executed, i went to get the value, length value at this time is covered.
2, let block-level scope, lift variable does not exist (js predetermined variable that is declared only). Js each cycle engine will re-declare the variable i is initialized once, the variable i is assigned only once every scope of this cycle, the value is not the same.

Guess you like

Origin www.cnblogs.com/jia-bk-home/p/11563352.html