Maison >interface Web >js tutoriel >Lorsque vous utilisez des fermetures dans des boucles JavaScript, comment pouvez-vous vous assurer que chaque fermeture capture la valeur correcte ?
Closures in JavaScript Loops: A Practical Example
In JavaScript, a common issue arises when using closures within loops, where the value of a variable captured by the closure is not the expected value.
Problem:
When defining functions within a loop using the var keyword, all functions reference the same variable outside the loop. This can lead to unexpected results, as seen in the code below:
<code class="js">var funcs = []; for (var i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value:", i); }; }</code>
Running this code prints "My value: 3" three times, even though we expect it to increment from 0 to 2.
Solutions:
ES6 Solution: Let
In ECMAScript 6 (ES6), the let keyword introduces block scope for variables, which solves this issue. Using let, each iteration of the loop creates a new variable i with a scope limited to the loop:
<code class="js">for (let i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value:", i); }; }</code>
ES5.1 Solution: forEach
In environments that support the Array.prototype.forEach function, we can leverage its unique nature to create distinct closures for each iteration. The callback function receives the current element of the array as a parameter, ensuring that each function captures a unique value:
<code class="js">var funcs = []; [0, 1, 2].forEach(function(i) { funcs[i] = function() { console.log("My value:", i); }; });</code>
Classic Solution: Closures
The classic solution is to create a closure that binds the variable to a specific value outside the loop. This is achieved by returning a new function that captures the desired value:
<code class="js">for (var i = 0; i < 3; i++) { funcs[i] = (function(i) { return function() { console.log("My value:", i); }; })(i); }</code>
By passing i as an argument to the inner function, we ensure that each closure captures the correct value.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!