Answer the question
In order to leave comments, you need to log in
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]();
Answer the question
In order to leave comments, you need to log in
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);
}
}
function generateArr() {
var arr;
for(var arr = []; arr.length < 100;arr.push(null));
return arr.map(function (_, i) {
return function () {
alert(i);
}
}
}
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 questionAsk a Question
731 491 924 answers to any question