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
myFunfunctions all reference the samet(andy) variable. So after the loop,tis1, so it always returns the 2nd value.You need to use a closure to “close” around the values (also, you shouldn’t use
for..infor arrays):