I'm working with a dynamically created function in a loop.
for (var i = 0; i < 4; i++) {
window["functiontest" + i] = function () { alert(i); }
}
It works, but not how I want to get it working. Because when I do this, it means when the functiontest0
will run it will alert "3" because it actually alerts var i
while the loop has finished adding to i
.
What I want is to somehow "hardcode" the current i
so it will actually alert "0" and not "3". I mean something like this:
window["functiontest" + i] = function () {
// I need just the current state for `i` here and
// not just the variable `i` - so for exampe I need
// it as `i` literally put 0
}
Is there any way I can force it to write the result into a "string" or something else?
THX for help guys. and sorry for duplicate couldnt find anything while searching for it. mostly because i couldnt explain it that well :-)
but i ended up with something like this:
for (var genfunc = 0; genfunc < 4; genfunc++) {
if (genfunc == 0) { //left
window["keyDown" + sys_curcontrols[genfunc]] = (function (unique) {
return function () { window["sys_keyLeft" + unique] = -1; }
})(nid);
}