0

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.

Dom
  • 2,980
  • 2
  • 28
  • 41
  • 2
    Use `const index = created.length` before the `created.push(…)` call - by declaring the variable *inside* the loop, your closure will use the correct value – Bergi May 21 '18 at 19:27

1 Answers1

2

Since primitive types are passed as values to the functions you could declare those functions using an immediate function invocation, something like:

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++;
    }
});
J. Pichardo
  • 3,077
  • 21
  • 37