Understanding the content of array elements

Asked

Viewed 78 times

1

const funcs = [];

for (let i = 0; i < 10; i++){
    funcs.push(function(){
        console.log(i);
    });
}

funcs[2]();
funcs[8]();

I would like to understand why the result, funcs[2]() and funcs[8](), were 2 and 8.

If the index starts at 0, the returns should not be 1 and 7?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

2 answers

7

You really should explain why you think it should be 1 and 7.

If we put to print what is the index of the last element of array it matches the value you print inside the function:

const funcs = [];
for (let i = 0; i < 10; i++) {
    funcs.push(function() {
        console.log(i);
    });
    console.log(funcs.length - 1, i);
}
console.log(funcs.length);
funcs[2]();
funcs[8]();

I put in the Github for future reference.

I’m taking the last available index by taking the property value length of array. I do the subtraction because the last element is always an index before the size, after all the first element of array is index 0, so the second is index 1 and so on. Note that it ends at 9 despite having 10 elements in the array

With this we can see that the value of i is always equal to the index value that the function was added to array.

Maybe you forgot in that part that the array starts at 0 and not at 1.

7

The index actually starts on 0, but the point is that in the loop, you are assigning a function that will give a console.log in the current index, so anyone you call will be equal to its own index:

funcs[0](); // mostra 0
funcs[1](); // mostra 1
funcs[2](); // mostra 2
...
funcs[9](); // mostra 9

Maybe it’ll be easier if you visualize it like this:

const funcs = [];
for (let i = 0; i < 10; i++){
    console.log("funcs["+i+"] vai mostrar: " + i);
    funcs.push(function(){
        console.log(i);
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.