Have you already guessed what we are going to do next? To search arrays in the loop!
We know what the initial index of the array is. It equals zero. Indices in the array increase by one. You can use a variable as an index.
It turns out that we can set a variable to zero, and then use it in a loop to access the elements of the array, increasing them by one at each iteration.
There is only one question: when to stop the loop? To do this, you need to know what the array length is.
And here, too, everything is excellent. Arrays can tell you about their length. To do this, use the .length command that knows about the number of elements in the array:
var numbers = [1, 2, 3, 4];
// Logs 4 in the console
By accessing length you can get the last element of the array, even if you do not know how many elements it holds:
someBigArray[someBigArray.length - 1];
Let’s analyze this expression. Suppose there are 100 elements in this large array. Its length will be equal to 100. The index of the last, hundredth, element will be 99 because the numbering in arrays starts from zero. Therefore, the index of the last element is calculated by subtracting one from the length.
With the command .length, you can consistently work with any arrays. That is, you can use the same code for calculations for arrays of arbitrary length.
var usersByDay = [812, 1360, 657, 1247];
The code has changed, click “Run” or turn autorun on.
On the second line, log usersByDay array length in the console.
On the next line, log the last element of the array in the console: usersByDay[usersByDay.length - 1].
On the next line, log the third from the end array element in the console using square brackets and length.
Now, in the first line, add the fifth element 1000 to the array usersByDay, separated by a comma and make sure that the console log function is working correctly.
Have you forgotten your password or lost access to your profile? Enter your email connected to your profile and we will send you a link to restore access.
Forgot to connect your email to the profile? Email us and we’ll help.