Here is created an empty paragraph in HTML, and given a id
to him:
<p id="demo"></p>
On the part of script
, in Javascript an object is created. An object can have a list of values, indicated by [ ]
or keys and values indicated by { }
.
An object can have other objects inside. In the case of your example, myObj
has 3 items, name
, age
and cars
:
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
};
The first two have values, the third has a list of values.
Then is made a loop
where i
starts from zero and increases while it is not the element size cars
(in the case, for as long as it is less than 3):
for (i = 0; i < myObj.cars.length; i++) {
The for
is composed of 3 essential expressions:
for( expressão inicial; condição para executar; operação a executar ao fim de cada iteração)
In the present case, initially i = 0
. The condition to end the for
is i < myObj.cars.length
. Each time the contents of { }
is executed, the i++
increases the value of i
in 1
The expression i++
amounts to i = i + 1
. Of curiosity, if instead of i++
were i += 7
the expression, i
increment of 7
in 7
.
If we wanted the size of myObj
instead of cars
would be myObj.length
instead of myObj.cars.length
. The estate length
is the one that returns the size.
In this case, this section will be executed 3 times, with i
ranging from 0 to 2.
x += myObj.cars[i] + "<br>";
Every "turn" of the loop, one of the cars would be caught, getting this value in x
:
Ford<br>BMW<br>Fiat<br>
Finally, the value of x
would be placed within the paragraph of the beginning of the code:
document.getElementById("demo").innerHTML = x;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
aqui é pego o elemento e o conteúdo HTML dele recebe o valor de `x`
What is your doubt?
– BrTkCa
This in the description .
– ManiacSaw
You spun that code ?
– Diego Souza
Yes, but being working doesn’t mean I understand ... hence I’m questioning that bit of Line code
– ManiacSaw