Concatenate string through for loop

后端 未结 2 1065
無奈伤痛
無奈伤痛 2020-12-31 11:01

I\'m trying to concatenate strings via for loop but i\'m receiving NaNs. What i want to achieve is to get one concatenated string Div #0, Div

相关标签:
2条回答
  • 2020-12-31 11:45

    Besides the selected answer, you could do this with a forEach if you have a list of stuff to put inside those divs:

    let string = '';
    items.forEach(item => string += '<div>'+ item.description + '</div>');
    
    0 讨论(0)
  • 2020-12-31 11:57

    Don't declare a new str variable inside the loop with var str. Reuse the one you declare outside the loop. Also do +=

    var divLength = $('div').length;
    
    var str = '';
    for(var i=0; i<divLength; i++){
      str += "Div #" + i + ", ";
      console.log(str);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>
    <div></div>
    <div></div>
    <div></div>

    0 讨论(0)
提交回复
热议问题