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 oft
in the function will always be equal to the last it had (ie 1) – Mahn Commented Feb 11, 2013 at 21:09
2 Answers
Reset to default 6The 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
评论列表(0条)