Home >Web Front-end >JS Tutorial >How to Pass the Correct Variable Value to a Function When Using Event Listeners in Loops?
How to Pass JS Variable Value to a Function
When iterating through arrays and adding event listeners to each element, the value of the loop counter variable may not be preserved as expected. Instead of capturing the current value, the listener uses the final value after the loop has terminated. To address this issue and pass the actual value (not the reference) to the function, consider the following approaches:
Modern Browsers:
Utilize the let or const keywords to declare block-scoped variables:
<code class="javascript">for (let i = 0; i < results.length; i++) { let marker = results[i]; google.maps.event.addListener(marker, 'click', () => change_selection(i)); }</code>
Older Browsers:
Create a separate scope to preserve the variable's value by passing it as a parameter to a nested function:
<code class="javascript">for (var i = 0; i < results.length; i++) { (function (i) { marker = results[i]; google.maps.event.addListener(marker, 'click', function() { change_selection(i); }); })(i); }</code>
By utilizing an anonymous function and passing the variable as an argument, you effectively pass its value to the function and create a closure. This ensures that each listener has access to the correct value at the time of creation.
The above is the detailed content of How to Pass the Correct Variable Value to a Function When Using Event Listeners in Loops?. For more information, please follow other related articles on the PHP Chinese website!