Variable that has a variable in its name

Asked

Viewed 64 times

1

In an exercise:

A company wants to know in how many months there was profit, that is, the balance greater than zero.

The code for resolution was this:

function quantidadeDeMesesComLucro(umPeriodo){
  let quantidade = 0;
  for(let mes = 0; mes < umPeriodo.length; mes++){
    if(umPeriodo[mes] > 0)
    quantidade += 1;
  }

return quantidade;
}

The doubt is in relation to the 4th line of the code in which it is expressed:

if(umPeriodo[mes] > 0)

How to understand umPeriodo[mes]? I can’t visualize how it works, considering umPeriodo = [100, -1, 10, 0].

1 answer

2


Ali gets a array. In addition to seeing the link previous would be good to understand well What is a variable?.

Then a array being variables within variables, you have to have a way of saying what is the array (is the name of the main variable in the umPeriodo), and the other party that picks up the internal variable in the array, therefore it is an index, usually numerical, as in a matrix (in JS it is possible that the index is different, but it seems that in this case it is numerical and sequential).

Then you can access umPeriodo[0] which is the first element of array umPeriodo. Can access umPeriodo[1] which is the second element, and so on.

Instead of the literal you can use a variable, so in each run that passes through there the index to be used will be the value of the variable, so let’s take the example:

mes is worth 0, so umPeriodo[mes] is actually the element umPeriodo[0], and when mes change to 1, then we will have umPeriodo[1], and so on.

You have a noose there that makes the value of mes change in each execution step, in each one it takes the corresponding element. This is how it is done to sweep the whole array (has other forms like for of).

  • Thanks. I totally get it!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.