创建javascript数组,其中每个元素都有一个函数,可以引用其在新数组中的位置
我试图获取一个字符串数组,并使用它们根据这些字符串的过滤子集创建一个对象数组。我需要我的对象包含一个方法,该方法可以访问所创建数组中该对象的位置 我尝试了以下方法:创建javascript数组,其中每个元素都有一个函数,可以引用其在新数组中的位置,javascript,Javascript,我试图获取一个字符串数组,并使用它们根据这些字符串的过滤子集创建一个对象数组。我需要我的对象包含一个方法,该方法可以访问所创建数组中该对象的位置 我尝试了以下方法: var strings = ["one", "two", "three"]; var created = []; var index = 0; jQuery.each(strings, function( i, item) { if( /*some condition about item*/ ) { c
var strings = ["one", "two", "three"];
var created = [];
var index = 0;
jQuery.each(strings, function( i, item) {
if( /*some condition about item*/ ) {
created.push(
{
myMethod: function() {
callSomething(index);
}
}
);
index++;
}
});
但明显的问题是,index
是一个变量,因此对callSomething
的任何调用都只会传递其当前值。我希望callSomething
在callSomething
定义时传递index
的值
我不能只使用jQuery中的索引(
I
),因为我不希望所有元素都出现在新数组中,只是一个筛选集。由于原语类型作为值传递给函数,因此可以使用即时函数调用来声明这些函数,例如:
var strings = ["one", "two", "three"];
var created = [];
var index = 0;
jQuery.each(strings, function( i, item) {
if( /*some condition about item*/ ) {
created.push(
{
myMethod: (function(idx) {
return function() {
callSomething(idx);
}
})(index)
}
);
index++;
}
});
由于原语类型作为值传递给函数,因此可以使用即时函数调用声明这些函数,例如:
var strings = ["one", "two", "three"];
var created = [];
var index = 0;
jQuery.each(strings, function( i, item) {
if( /*some condition about item*/ ) {
created.push(
{
myMethod: (function(idx) {
return function() {
callSomething(idx);
}
})(index)
}
);
index++;
}
});
在
created.push(…)
调用之前使用const index=created.length
-通过在循环中声明变量,闭包将使用正确的值在created.push(…)
调用之前使用const index=created.length
-通过在循环中声明变量,您的闭包将使用正确的值