Javascript array with callback function

I tried to better understand JavaScript. Here is a piece of code that I read from closing JavaScript functions .

var funcs = []; // create a bunch of functions for (var i = 0; i < 3; i++) { funcs.push(function() { console.log(i); }) } // call them for (var j = 0; j < 3; j++) { funcs[j](); } 

The funcs array has a push callback function. I don’t understand why in the J loop, funcs[j]() will call this function to print i in the console.
I tried to understand this sequence by adding a few console messages:

 var funcs = []; console.log("start"); for (var i = 0; i < 3; i++) { console.log("i:" + i); funcs.push(function(){ console.log(i); }) } console.log("J loop"); for (var j=0; j<3; j++) { console.log("j:" + j); funcs[j](); } 

As expected, there are 3 for all three functions.
My question is: how funcs[j]() call the funcs.push(...) function? I understand that funcs[j] refers to the J element of the funcs array. But why will the brackets () call the push(...) function?

+5
source share
2 answers

function() {console.log(i);} is an expression that evaluates a value, which is a function that registers i .

funcs.push is a function that adds a value to an array.

Enter () after calling this function by function.

funcs.push(some_value) calls the push function and passes some_value as the value placed in the array.

funcs.push(function() {console.log(i);}) adds the function to the array.

The value of funcs[0] becomes this function.

Enter () after calling this function by function.

funcs[0]() calls the function, which is the first value in the array.

+2
source

Firstly, the variable "i" is global and completes the loop, i = 3 Then the functions inside the funcs use the variable "i", then all the functions print "3" in the console.

Perhaps you wanted to do this:

 var funcs = []; console.log("start"); for (var i = 0; i < 3; i++) { console.log("i:" + i); funcs.push(function(i){ console.log(i); }) } console.log("J loop"); for (var j=0; j<3; j++) { console.log("j:" + j); funcs[j](j); } 
-1
source

Source: https://habr.com/ru/post/1245494/


All Articles