Home  >  Article  >  Web Front-end  >  How to Preserve Variable Values When Passing Arguments to Functions Inside Loops?

How to Preserve Variable Values When Passing Arguments to Functions Inside Loops?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 22:00:30254browse

How to Preserve Variable Values When Passing Arguments to Functions Inside Loops?

Preserving Variable Values When Passing Arguments to Functions

When working with JavaScript loops, you may encounter situations where you need to preserve the value of a variable when passing it to a function. This scenario arises when the variable's value might change during the loop execution, leading to unexpected behavior in event listeners.

Consider the following example:

<code class="js">for (var i = 0; i < results.length; i++) {
    marker = results[i];
    google.maps.event.addListener(marker, 'click', function() {
        change_selection(i);
    });
}

In this code, the event listener is attached to each marker within the loop. However, when the listener is triggered, it uses the final value of i, which is the length of the results array when the loop ends. This behavior is undesirable as it results in the same value being used for all event listeners.

To preserve the value of i for each listener, you can utilize block-scoped variables (in modern browsers) or closures (in older browsers).

Modern Browsers (ES6):

<code class="js">for (let i = 0; i < results.length; i++) {
    let marker = results[i];
    google.maps.event.addListener(marker, 'click', () => change_selection(i));
}</code>

Using the let keyword creates a block-scoped variable that is only accessible within the loop. This ensures that each event listener has its own copy of the i value at the time of creation.

Older Browsers:

<code class="js">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>

Creating an anonymous function and calling it with i as the first argument creates a closure. The function preserves the value of i at the time of its creation, ensuring that each event listener uses the correct value for its specific marker.

The above is the detailed content of How to Preserve Variable Values When Passing Arguments to Functions Inside Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn