Object loop function override javascript?
I am 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 is it returning the second array?
here's the jsFiddle
source to share
The function myFun
executes all references to the same variable t
(s y
). Therefore, after the cycle t
has 1
, so it always returns the 2nd value.
You need to use closures to "close" around 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());
source to share
Since you are using JQuery, you have a simple method for iterating through arrays without having to worry about specifically capturing the current value of your index when creating a closure. This $.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])} ;
});
source to share