Saturday, January 27, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...