JS loop variable out of scope


See the following code

var li = document.querySelectorAll('li');
for(var i = 0; i<10; ++i){
li[i].oncilck=function(){
console.log(i);//无论点击哪个li都会输出10
}
}

Why is this so?
This is because the timer and event handlers as well as the Ajax callbacks, asynchronous tasks belong
asynchronous task execution that is not in the mainline Cheng Zhongli, but into the task queue, so if the asynchronous tasks into a for loop and asynchronous tasks variables used in the function cycle, when the asynchronous task removed from the task execution queue, the cycle already completed, the loop variable has exceeded the ideal value, resulting in errors

Then there is the question of why the loop variable can also be accessed outside the loop? Look here .

Solution

1. Closures

var li = document.querySelectorAll('li');
for(var i = 0; i<10; ++i){
	(function(i){
		li[i].oncilck=function(){
		console.log(i);
	})(i)

}
}

Each time the execution cycle, the current i will be passed as arguments to execute the function immediately, this time, the innermost event handler is not for the for loop i loop variable i, but the immediate execution of the function parameter i (when the inner function access for the loop variable, is executed immediately replace the function parameters, and the event handler is not triggered, then immediately execute the function can not be executed, the local variables will not be written off)

2. let the loop variable declaration

In another article written in great detail .

Declared variables let keyword that has the block-level scope, var variables declared properties do not have block-level scope.

for(let i = 0; i<10; ++i){
}
console.log(i);//not defined

Use the let keyword to declare the loop variable in the loop can be prevented through the bad in the end, you can still access

Released eight original articles · won praise 0 · Views 116

Guess you like

Origin blog.csdn.net/qq_43915356/article/details/105176267