Saturday, 27 January 2018

javascript closure for_loop

I have been stuck on this for a while. I had also threw in a debugger to see what is actually happening. I think it is something related to closure but not 100% sure.



var names = [ "roy", "nick" ];

var ids = [0, 1];
var people = [];

for ( i in names ){
people.push({
name: names[i],
id: ids[i]
})
people[i].ages = {
this_year: function(){

var ages = [10, 11];
return ages[i];
}
}
}
console.log(people[0].ages.this_year()); // why not 10






Tried using function arguments as suggest by @slebetman, however, i intend to invoke the function later so this wouldn't work..



var names = [ "roy", "nick" ];
var ids = [0, 1];
var people = [];

for ( i in names ){
people.push({
name: names[i],
id: ids[i]

})
people[i].ages = {
this_year: (function(x){
var ages = [10, 11];
return ages[x];
})(i)
}
}
console.log(people[0].ages.this_year); // 10
console.log(people[0].ages.this_year()); // not a function

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...