Here is an empty paragraph in HTML, and given a id
to it:
<p id="demo"></p>
In the script
part, an object is created in JavaScript. 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.
Next, a% w / w is made, where w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w
for (i = 0; i < myObj.cars.length; i++) {
The loop
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 this case, initially i
. The condition for ending cars
is for
. Each time the content of i = 0
is executed, for
increases the value of i < myObj.cars.length
to { }
The expression i++
is equal to i
. Curiously, if instead of 1
was i++
expression, i = i + 1
would increment from i++
to i += 7
.
If we wanted the size of i
instead of 7
would be 7
instead of myObj
. The cars
property is the one that returns the size.
In this case, this section will be executed 3 times, with myObj.length
ranging from 0 to 2.
x += myObj.cars[i] + "<br>";
At each "loop" of the loop, we would get one of the cars, getting this value in myObj.cars.length
:
Ford<br>BMW<br>Fiat<br>
Finally, the value of length
would be put inside the beginning paragraph of the code:
document.getElementById("demo").innerHTML = x;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
aqui é pego o elemento e o conteúdo HTML dele recebe o valor de 'x'