Concatenate sum of number to a string

2

I want to concatenate a sum from a number to a string in JavaScript and had to resort to an auxiliary variable.

What I did first (incorrect example):

for (var i; i < x; i++)
  h = "texto" + x+1 + ".txt";

Then:

 for (var i; i < x; i++){
         var a = i+1;
         h = "texto" + a + ".txt"; 
 }

Any solution for me to avoid that auxiliary variable?

Note: This is not the code I'm working on right now, it's just to exemplify my problem. The solution to change% w / o% by% w / o% does not apply in my case.

    
asked by anonymous 27.07.2015 / 15:57

2 answers

3

Simply because there is a logic error in the first version. Where are you doing x + 1 , and in the second version i + 1 . I believe that whatever you want is i + 1 . Also to an operator precedence problem, which can be solved by circling the calculation with (i+1) kernels, causing it to be executed before the concatenation. In addition to the problem of not adding initial value to i in for : for (var i = 0; i < x; i++) , which here for me also did not work.

Here is example 1 corrected (Check the output in the console of your browser (F12), after having run the snippet):

var x = 5;

for (var i = 0; i < x; i++){
  var h = "texto" + (i+1) + ".txt";
  console.log(h);
}
    
27.07.2015 / 16:14
3

For me neither works, the problem is in the statement of for :

for (var i = 0; i < 10; i++) {
  h = "texto" + i + 1 + ".txt";
  print(h);
}

See running on ideone .

    
27.07.2015 / 16:20