jquery - object function loop override javascript? - Stack Overflow

i'm very confused about the following code : var x =[ {name : 'name1' , value : 15 },{na

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

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

Share asked Feb 11, 2013 at 21:02 Mina GabrielMina Gabriel 25.3k26 gold badges100 silver badges128 bronze badges 2
  • Just a heads-up the for-in loops are for iterating over members in an object. Use for(var i=0; i < anArray.length; i++){anArray[i]} to iterate over an array. – kimpettersen Commented Feb 11, 2013 at 21:06
  • 1 The actual problem lies in console.log(y[t]), since the value of t in the function will always be equal to the last it had (ie 1) – Mahn Commented Feb 11, 2013 at 21:09
Add a ment  | 

2 Answers 2

Reset to default 6

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])} ;
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744827146a4595863.html

相关推荐

  • jquery - object function loop override javascript? - Stack Overflow

    i'm very confused about the following code : var x =[ {name : 'name1' , value : 15 },{na

    2天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信