Ah, the dreaded closure issue strikes again. ) The problem is that function defined within the loop just 'knows' that it should work with variable named i
('closures' around it) - but it doesn't know anything about the value of i
at the very moment it's defined. Have you looked for closure issue
, you'd have found plenty of similar issues here at SO. They both have one thing in common: there's a function defined (as event handler or timeout callback) within the loop, and that function somehow deals with the loop variable (or some value based on it).
One common solution to this problem is explicitly localizing loop variable for this function. For example:
b[i] = (function(i) {
return { text: temp[i], onclick: function(){alert(temp[i])}};
})(i);
Explanation: at each step of the loop you create and immediately invoke (!) a function taking current value of i
as an actual argument. This way the function it creates (as onclick
handler, in this example) no longer works with 'closured' i
- but a local one.
This - wrapping a function definition into another function - is a generic solution for this type of issues. But in this particular case it could be optimized:
b[i] = (function(tempVal) {
return { text: tempVal, onclick: function(){alert(tempVal)}};
})(temp[i]);
... as you only work with temp[i]
value here, and i
alone is not used anywhere.