17

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>

6 Answers 6

34

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Bah, silly me. I guess 3am aint the best time to see such small things x).
I've never seen that [i] wasn't a syntax error, but still, it can just be i.
Right! When you do "" + [i] the array is converted to a comma separated string of it's elements. And in the case of [i], an array of one element, lets say that i = 1 that would be "1". I edited the answer accordingly
@RedMercury Oh, of course. Somehow [i] looks so much like an index accessor that I couldn't see the array.
11

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>');

Comments

3

From Typescript ESLint recommendations,

For cases where the index is only used to read from the array being iterated, a for-of loop is easier to read and write.

We can use for-of using the keys method.

let str = ''
for (const i of Array(divLength).keys()) {
  str += `Div #${i}, `;
}
console.log(str);

But that has the problem of the trailing comma. We can let JavaScript take care of that using the join method.

const arr = Array.from(Array(divLength).keys()); // [ 0, 1, 2];
const divArray = arr.map(n => `Div #${n}`)       // ['Div #0', 'Div #1', 'Div #2']
const str = divArray.join(', ');                 // 'Div #0, Div #1, Div #2'

which can be wrapped up as a one-liner,

const s = Array.from(Array(divLength).keys()).map(val => `Div #${val}`).join(', ')

A somewhat less verbose one-liner can be done using fill method

const s = Array(divLength).fill().map((_, i) => `Div #${i}`).join(', ')

Comments

0

If we are concatenating the string for an array then you can do like this. For loop is also best solution but it becomes vast process:

if(this.questionData.length > 0) {
    this.questionData.forEach(questions => {this.questionsParams += '&question'+ questions.question +'=' + questions.value;
    });
}

Perfect solution output like this : &question1=1&question2=0&question3=1&question4=0

Comments

0
let str = ''
for (let i = 0; i < arr; i++) {
   str += `${arr[i]}`
}

This worked in my case.

Comments

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

var str = '';
for (var i=0; i<divLength; i++) {
  var str += `Div # ${i} , `;
  console.log(str);
}

Should work jus fine. You have to add ${i} to the string inside or it will give u NaN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.