How to add values from several strings to another without this string losing its value?

Asked

Viewed 47 times

0

I’m going to add values to a variable inside a for as follows:

function gerarcods(){
    var alfa = $("#nalfa").val();
    var qtdcods = $("#nqtdcods").val();
    codigos = "";
    for(i = 1; i<= qtdcods; i++){  
        str = alfa+i+",";
        res = codigos.concat(str);
    }
 }

However, this way, the value of res is superimposed (obviously). The intention is that the string looks like this: "alfa1,alfa2,alfa3...". I wonder if there is a function to add a content to the string without losing its previous value.

2 answers

0


Put an operator in front of that:

str += alfa+i+",";

I believe that part of the job can go after the for and not inside:

res = codigos.concat(str);

0

You need to set the variable res before and go concatenating with +=. But I didn’t see the need for the variable codigo nor the method concat:

function gerarcods(){
    var alfa = $("#nalfa").val(),
        qtdcods = $("#nqtdcods").val(),
        res = '';
    for(i = 1; i<= qtdcods; i++){  
        res += alfa+i+",";
    }
    
    console.log(res);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="nalfa" value="alfa">
<input type="number" id="nqtdcods" value="2">
<br>
<button type="button" onclick="gerarcods()">Gerar</button>

Browser other questions tagged

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