i'm very confused about the following code :
var x =[ {name : 'name1' , value : 15 },{name :'name2' , value: 60} ];
var y = [[1,2,3] , [4,5,6]] ;
for(var t in y){
x[t].myFun = function(){console.log(y[t])} ;
}
console.log(x[0].myFun()) ;
shouldn't this code return the first array in y why does it return the second array ?
here is a jsFiddle
The myFun functions all reference the same t (and y) variable. So after the loop, t is 1, so it always returns the 2nd value.
You need to use a closure to "close" around the values (also, you shouldn't use for..in for arrays):
var x = [{name : 'name1' , value : 15 }, {name :'name2' , value: 60}];
var y = [[1,2,3] , [4,5,6]];
for(var t = 0, len = y.length; t < len; t++){
(function(t){
x[t].myFun = function(){console.log(y[t])};
})(t);
}
console.log(x[0].myFun());
Since you're using JQuery, you have a simple method to iterate arrays without the needing to worry about specifically capturing the current value of your index when creating a closure. It's $.each:
var x =[ {name : 'name1' , value : 15 },{name :'name2' , value: 60} ];
var y = [[1,2,3] , [4,5,6]] ;
$.each(y, function(i,v)
{
x[i].myFun = function(){console.log(y[i])} ;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With