I just learn about array today but I don't actually understand this code I'm learning.
let units = [1, 10, 100, 1000, 20];
for(let i = 0; i < units.length; i += 1){
console.log(units[i]);
}
How would console.log(units[i]);
return 1
, 10
, 100
, 1000
, 20
and not 5
?
Could you guys explain to me the way I will actually understand this?
units
is an array.
units[0]
gets you the first item in the array (1). units[1]
gets you the next item in the array (10). and so on.
So as i
is incremented with each loop iteration, you get the corresponding item from the list.
Just for your information.
This below is the initialization of list of numbers in a variable units
let units = [1, 10, 100, 1000, 20];
Now the loop begin.
for()
is the loop.
Where 1st params let i=0
tell the starting point of the array.
2nd params i<units.length
defined the length of array where the loop needs to be end
3rs params tell the index need to be increment each time the loop executed. For eg: when index i
is 0, then value units[i] = 1
. After its execution the value of index i
is incremented by 1 due to i++
as third param of for()
loop.
The loop will continue until it meets the value of last index defined in second params that is i<units.length
for(let i = 0; i < units.length; i += 1){
console.log(units[i]);
}
I hope it made you clear.
You are both declaring that a variable units
exists and you are putting elements in the array with your statement
let units = [1, 10, 100, 1000, 20];
This has created an array with 5 elements; array elements are numbered (indexed) starting at zero :
| 1 | 10 | 100 | 1000 | 20 | // array with elements in it
0 1 2 3 4 // positions of elements
— the first element in the array is at position 0
that is, the item at units[0]
is 1
, the item at units[1]
is 10
, etc.
Now you start your loop, using the variable i
as a number to use as an index into the array.
When i === 0
then units[i]
is asking for the element at position units[0]
, which is 1,
when i === 1
then units[i]
is asking for the element at position units[1]
, which is 10,
and so on.
So when you say console.log(units[i]);
you are not printing the value of i
; you are getting the element in the array units
that is at position i
in the array and printing that .
console.log(units[i])
when i === 3
gets the item in the array at position 3, which is 1000
, so it prints 1000.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.