[英]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 ? 不应该这个代码返回y
的第一个数组为什么它返回第二个数组?
The myFun
functions all reference the same t
(and y
) variable. myFun
函数都引用相同的 t
(和y
)变量。 So after the loop, t
is 1
, so it always returns the 2nd value. 所以在循环之后, t
为1
,所以它总是返回第二个值。
You need to use a closure to "close" around the values (also, you shouldn't use for..in
for arrays): 你需要使用一个闭包来“关闭”值(同样,你不应该使用for..in
表示数组):
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. 由于您正在使用JQuery,因此您可以使用一种简单的方法来迭代数组,而无需担心在创建闭包时专门捕获索引的当前值。 It's $.each
: 这是$.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])} ;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.