I have a code that kind of follows this pattern:
a = "abcdefghijklmnopqrstuvwxyz";
m = {};
for(i=0;i<10;i++){
m[a.charAt(i)] = function(){
return i;
};
}
console.log(m.c());
it returns 10.
WHY the heck does it do that? And how could I get it to return the corresponding number?
------- EDIT -------
Thank for your great responses. The answers that have been provided so far work for the above example, but I forgot to mention that I need to pass a callback function. Taking your advice into consideration I came up with this:
a = "abcdefghijklmnopqrstuvwxyz";
m = {};
f = function(i) {
return function(){
return i;
}
}
for(i=0;i<10;i++){
var eval('n') = "hi";
console.log(n);
m[a.charAt(i)] = function(fn){
fn(f(i));
};
}
m.c(function(a){console.log(a);});
and the outcome agreed with my intuition that it would not work. Does anyone have any ideas for this?
Thanks for your help
As a result of your help here I was able to start this project: https://github.com/sbussard/python-for-node
Please feel free to continue to contribute as you wish.