SoFunction
Updated on 2025-04-07

A brief discussion on the issue of outputting i to the same value by js for loop

1. I have encountered a problem in development recently. Why is the output 5 each time instead of clicking on each p, and the corresponding 1, 2, 3, 4, 5 will be alerted.

The code is as follows:

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>Closure Demo</title> 
</head>  
<body>  
<p>1</p>  
<p>2</p>  
<p>3</p>  
<p>4</p>  
<p>5</p> 
<script type="text/javascript">
=function() {  
 var ps = ("p");  
 for( var i=0; i<; i++ ) {  
   ps[i].onclick = function() {  
   alert(i);  
 }  
 }  
}  
</script> 
</body>  
</html>

At this time, click any p to pop up 5

Causes of occurrence:The js event processor will not run during idle time of thread, resulting in the output of the last value of i when it is run, i.e.: 5

2. Solution: Use closures to protect the value of variable i.

//sava1: Add a layer of closure, i is passed to the inner function in the form of function parameters for( var i=0; i<; i++ ) {  
 (function(arg){   
  ps[i].onclick = function() {   
   alert(arg);  
  };  
 })(i);//Articles when calling } 


//save2: Add a layer of closure, i is passed to memory function in the form of local variables for( var i=0; i<; i++ ) {  
 (function () {  
  var temp = i;// Local variables when calling  ps[i].onclick = function() {  
  alert(temp);  
  }  
 })();  
 }


//save3: Add a layer of closure and return a function as a response event (note the subtle difference from 3) for( var i=0; i<; i++ ) {  
 ps[i].onclick = function(arg) {  
  return function() {//Return a function  alert(arg);  
  }  
 }(i);  
 } 


//save4: Save the variable i to each paragraph object (p) for( var i=0; i<; i++ ) {  
  ps[i].i = i;  
  ps[i].onclick = function() {  
  alert();  
  }  
 }


//save5: Save the variable i in the anonymous function itself for( var i=0; i<; i++ ) {  
 (ps[i].onclick = function() {  
  alert();  
 }).i = i;  
 }   
} 


//save6: Implemented with Function, in fact, every time a function instance is generated, a closure will be generated. for( var i=0; i<; i++ ) {  
  ps[i].onclick = new Function("alert(" + i + ");");//new generates one function instance at a time } 


//save7: Use Function to implement it, pay attention to the difference between it and 6 for( var i=0; i<; i++ ) {  
   ps[i].onclick = Function('alert('+i+')'); 
 }

The above brief discussion on the issue of js for loop output i to the same value is all the content I share with you. I hope you can give you a reference and I hope you support me more.