asax asax - 1 month ago 7
Javascript Question

Javascript: how to add string values generated from loop

I have a for loop:

for(var data = 1; data <=10; data++){
var data = $array[data];
var allData = allData + ", " + data;
};


for eg:

var data = $array[1] value is "apple"
var data = $array[2] value is "carrot"


when I loop:

var allData = allData + ", " + data;


I want:

var allData = apple, banana


The above add of string:


var allData = allData + ", " + data;


is not working.

How can I fix it?

Answer

I think this is what you're looking for:

var allData = $array.join(', ');

This will turn the array to a string, with a comma in between each value.

or

This is how you can fix your logic the current way you're doing it: You want to declare the allData var above the loop, otherwise every iteration will redeclare the var, overwriting the previous one. Then you can use the += operator to add to the current value. Also I fixed the loop syntax a little.

var allData = '';
for (var i = 0; i < $array.length; i++) { 
    var data = $array[i];
    if(i == 0) allData += data;
    else allData += ", " + data;
};

https://jsfiddle.net/L7ch8u9b/

Comments