I'm trying to take an array of strings and use them to create an array of objects based on a filtered subset of those strings. I need my objects to contain a method which has access to that objects position in the created array.
I've tried the following:
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++;
}
});
But the obvious problem is that index
is a variable, so any calls to callSomething
will just pass its current value. I want callSomething
to pass the value of index
at the time of callSomething
's definition.
I can't just use the index (i
) from jQuery's each, because I don't want all elements to end up in the new array, just a filtered set.