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.
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
– Maniero