Reputation: 885
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>
Upvotes: 17
Views: 115278
Reputation: 1
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
Upvotes: 0
Reputation: 533
let str = ''
for (let i = 0; i < arr; i++) {
str += `${arr[i]}`
}
This worked in my case.
Upvotes: 0
Reputation: 123
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(', ')
Upvotes: 3
Reputation: 4310
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>
Upvotes: 33
Reputation: 1
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
Upvotes: 0
Reputation: 1675
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>');
Upvotes: 11