Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string through for loop

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 #1, Div #2, Div #3,.

var divLength = $('div').length;

var str = '';
for(var i=0; i<divLength; i++){
  var 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>
like image 667
nehel Avatar asked Sep 20 '16 00:09

nehel


1 Answers

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>
like image 62
Red Mercury Avatar answered Oct 09 '22 11:10

Red Mercury