Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object function loop override javascript?

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

like image 605
Mina Gabriel Avatar asked Dec 06 '25 17:12

Mina Gabriel


2 Answers

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()); 
like image 89
Rocket Hazmat Avatar answered Dec 08 '25 05:12

Rocket Hazmat


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])} ;
});
like image 20
Plynx Avatar answered Dec 08 '25 05:12

Plynx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!