How to add values from multiple strings to another without losing this value?

0

I want 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, in this way, the value of res is superimposed (obviously). The intention is that the string looks like this: "alpha1, alpha2, alpha3 ...". I would like to know if there is a function to add a content to the string without losing it's previous value.

    
asked by anonymous 21.02.2018 / 02:47

2 answers

0

Place an operator in front of this:

str += alfa+i+",";

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

res = codigos.concat(str);
    
21.02.2018 / 02:51
0

You need to set the variable res before and go concatenating with += . But I did not see the need for the codigo variable or the concat method:

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><inputtype="text" id="nalfa" value="alfa">
<input type="number" id="nqtdcods" value="2">
<br>
<button type="button" onclick="gerarcods()">Gerar</button>
    
21.02.2018 / 02:54