Consider an object obj
any:
obj = {q: 1, w: 2, e: 3, r: 4, t: 5, y: 6};
Now I'm iterating under the object's keys and creating an anonymous function that uses this key:
list = []
for (var key in obj) {
list.push(function() {
return key;
});
}
But this does not work: console.log(list[0]()) // isso mostra "y"
. It is as if the variable key
used was always that of the last iteration and not that of the iteration that created the function. Modifying this does not solve the problem:
list = []
for (var key in obj) {
var dummy = key;
list.push(function() {
return dummy;
});
}
Even though I have created a different variable in each iteration and referred to its value specifically, the result is the same. Not even writing something like the following works.
list = []
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
list.push(function() {
return key;
});
}
Why? What's going on here? How to write a code that does the proposed?