How to increment number to a variable in JS?

Asked

Viewed 424 times

0

I want to know how to increment a number to a JS variable every time it goes through the while loop. For example:

var num2 = 1;

while(num2 < num){
    new google.maps.Marker({
        position: posicao(incrementar valor de num2 aqui),
        title: nome(incrementar valor de num2 aqui),
        map: map
    });

    num2++;
}
  • But you’re already doing it...

  • No, man. I want the value of num2 to be increased to the position and name variables. Like, they’ll start as: posicao1 and name1, then posicao2 and Nome2, and so on.

  • But position and title sane strings ? You can give examples of values they have ?

  • Guys, solving this problem would also help me: https://answall.com/questions/309026/como-chamar-fun%C3%A7%C3%A3o-js-via-php. Since I’m only trying this way used in this post because I didn’t get the link post way

  • Isac, both are variables that are receiving BD values, for example: position: -9.838877963370699 -39.485223973571806 and name: test marker

  • The use of eval() is not very recommended, but in these cases I see no problem: position: eval('posicao'+num2),

  • I suggest making the question as clear as possible, to avoid that those who answer have to edit several times because they have not got exactly what you want. Put an example of position and title before and after being "increased".

  • People, with the link(https://jsfiddle.net/qc0g5j8f/) @dvd posted already solved the problem. Thank you all

Show 3 more comments

1 answer

2


You can do so by creating 2 variables by concatenating to the variable:

var num2 = 1;

while(num2 < num){

   var posicao = "posicao"+num2;
   var nome = "nome"+num2;

    new google.maps.Marker({
        position: posicao,
        title: nome,
        map: map
    });

    num2++;
}
  • Like this, it worked, but only in the concatenation part. Like this, what I’m doing is the following: I read the BD data, pass them by echo via variables like posicao1, nome1, posicao2, Nome2. Only when reading the data in JS to add the markers on the map, I

  • Just as?....

  • Since, in this case, posica1, name1, posicao2, Nome2 and so on are variables that I need to capture them

  • It is very confusing since I am using several languages at the same time, but it is already working normally, so much so that if you just do one if asking for it only that position and name, type, posicao3 and name3, it will read exactly the requested data. But since I don’t know how many markers I need a loop

  • Do the test using Eval() as I put there in the comments.

  • Thus: https://jsfiddle.net/qc0g5j8f/3/

  • 1

    Exactly! Man, thank you so much, you saved me a lot of headache.

Show 2 more comments

Browser other questions tagged

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