Skip to content Skip to sidebar Skip to footer

Adding Functions To Javascript's Array In A Loop

I'm try to creat array with functions in a loop. But I think don't get something about encapsulation. For example this code returns 'y y'. Live demo. HTML
&

Solution 1:

This is due to the way closures work in JavaScript.

You want something like this:

for (var key in json) {
    (function(key) {
        my_array.push(function() { 
            div.innerHTML = div.innerHTML + ' ' + json[key];
        });
    })(key);
}

In JavaScript, closures or anonymous functions are lexically bound to the scope in which they are defined. What this means is that they have access to all variables that have been defined in the scope in which the closure is also defined.

So in your original code, you have key, which initially points to 1. In your function, you have json[key], which originally is json[1], which is x. Then when the loop goes to the next iteration you have key set to 2. But the thing is that key in the first function instance and the second function instance both point to the same location. So when you finally evaluate the function, they will use whatever value key has at the time of execution. At the time of execution, key is set to 2 because that was the last value of key at the end of the loop.

To fix this, you have to introduce a new scope by using an anonymous, self-invoked function. By using this pattern, you deliberately introduce a new scope such that key in this new scope has its own location and is different from key in the outer scope.

Check out the updated fiddle.

Post a Comment for "Adding Functions To Javascript's Array In A Loop"