W
W
webvlassov2015-01-21 22:24:12
JavaScript
webvlassov, 2015-01-21 22:24:12

How to write a function that will output an array of functions that output the array's serial number?

The task itself sounds like this: The programmer planned to create an array of 100 functions, each of which displays its serial number in this array. When checking, it does not display what is needed. Fix the programmer's mistake.

function FunctionArray(count)
{
    var arr = [];
    for (var i = 0; i < count; i++) {
        arr[i] = function() { alert(i) };
    }
    return arr;
}

var i=100;
var arr = FunctionArray(i);

//Проверка
arr[0]();

I tried different ways, but all the same, when calling any f-ii from the array, 100 is displayed.
Please help me deal with this issue, thanks!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-01-21
Protko @Fesor

All your functions refer to the same value - i. In order for everything to work at the time of defining the function, this value must be stored.

function generateArr() {
    var arr = [];
    for (var i = 0; i < count; i++) {
        arr[i] = makeFunction(i);
    }
    return arr;
}

function makeFunction (i) {
    return function () {
        alert(i);
    }
}

my code above will work, because when passing a variable as an argument to a function, the value is copied (well ... not really, all sorts of copy-on-write are applied there, but still the essence is the same).
To make it a little better...
function generateArr() {
    var arr;
    for(var arr = []; arr.length < 100;arr.push(null));

    return arr.map(function (_, i) {
        return function () {
           alert(i);
        }
    }
}

W
webvlassov, 2015-01-21
@webvlassov

Thank you very much, I seem to understand the essence of the solution of the problem.
As I understand it, you can also rewrite this function like this:

function FunctionArray(count) {
    var arr = [], i;
    for (i = 0; i < count; i++) {
         (function(index){
              arr.push(function(){ alert(index) });
         }(i));
    }
    return arr;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question