Maison > Article > interface Web > Les fermetures JavaScript à l’intérieur des boucles peuvent-elles rompre la portée des variables ?
In JavaScript, a common issue arises when using loops to create functions that log their index or value. Despite intending to log different values, all functions often end up logging the same value due to the nature of variable scoping.
Consider the following code:
<code class="javascript">var funcs = []; for (var i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value:", i); }; } for (var j = 0; j < 3; j++) { funcs[j](); // Outputs: "My value: 3" three times }</code>
Instead of outputting "My value: 0", "My value: 1", and "My value: 2", it logs "My value: 3" three times. This behavior persists across different scenarios, including using event listeners or asynchronous code.
ES6 introduces the let
keyword, which creates variables scoped to their enclosing block. Using let
in the loop ensures that each function has its own distinct variable:
<code class="javascript">for (let i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value:", i); }; }</code>
For scenarios involving iterating over arrays, the forEach
method provides a convenient solution. Each callback in the forEach
loop has its own closure, providing a unique variable for each iteration:
<code class="javascript">someArray.forEach(function(arrayElement) { console.log("My value:", arrayElement); });</code>
In older JavaScript versions, closures can be used to bind a variable to a specific value within a function:
<code class="javascript">var funcs = []; function createfunc(i) { return function() { console.log("My value:", i); }; } for (var i = 0; i < 3; i++) { funcs[i] = createfunc(i); }</code>
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!