Concatenate number sum to a string

Asked

Viewed 1,623 times

2

I want to concatenate a sum of 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";

Afterward:

 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 with at the moment, it’s just to illustrate my problem. The exchange solution i++ for ++i, does not apply in my case.

  • 1

    Have you tried this? "texto" + (x+1) + ".txt"

  • No --', thanks mustache

  • In both versions you’re using the x differently. You can explain the role of x in the question?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

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 whatever you want to be i + 1. Also to a previous problem of operators, which can be solved by circulating the calculation with parentheses (i+1), making it run before concatenation. In addition to the problem of not adding initial value to i in the for: for (var i = 0; i < x; i++), that here for me also made it not work.

Follow example 1 corrected (Checks the output in your browser console(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);
}

3

Browser other questions tagged

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