In the first line you give, for(var i=0; i < cartas.length; i=i+1)
its operation is like this: for
is a reserved word of the language that waits for parentheses where you will define how the cycle will be done:
a) first receive a initialization , that is, define how the cycle will start ( var i=0
, declare a variable i
whose value will be 0);
b) secondly what is the condition for the cycle to stop ( i<cartas.length
, that variable i
has to be less than the length of the array cartas
);
c) finally receives the increment ( i=i+1
indicates that each time you finish doing what is inside the block for
to that variable i
will add 1).
That also responds to the first line of the code that you set as an example but changing the array cartas
for the array palos
. The following:
for (var j = 1; j <= 12; j = j + 1)
Indicates that you will initialize the variable j
and assign it the value 1
, repeat the cycle while j
is less than or equal to ( <=
) 12 and increase j
at the end of the task will be one ( j=j+1
).
Finally,
baraja[baraja.length] = { p: palos[ i ], v: j };
works like this:
The array baraja
in the position baraja.length
(the position in an array you place with the square brackets, []
) will be an object whose property p
will be what contains the fix palos
in position i
, as well as its property v
will be the current value of j
.
By parts:
-
In JavaScript you can define objects by just using the {}
keys. Using this notation:
{
clave: valor
}
which is what you mean by dictionaries . In your example:
{
p: palos[i], // posiblemente "Palo"
v: j // posiblemente "Valor"
}
-
Also in JavaScript, you can add a value to an array in several ways. For that matter, what you're doing is like this:
If the array arr
has 3 positions ( ["a", "b", "c"]
), its length is 3. Remember that its indexes ( positions ) start at 0, so both arr[0]
= "a"
.
If you assign a value in a position that does not exist (for example, arr[3]
, remember that your last index is arr[2]
) then add it.
(Remember that the comparison is with two ==
, including 3 ===
, while the assignment is with only one =
).
Therefore, when using the new index baraja.length
you are creating a new element in the array, and that object will be a dictionary with a value for p
and a value for v
.
The latest JavaScript magic: you can access it in two ways:
baraja[1]["p"] // "Notación Corchetes"
baraja[1].p // "Notación Punto"