0

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?

2
  • don't redeclare your variable.... Commented Nov 3, 2016 at 19:11
  • In your for loop, you're redefining/overwriting data, which causes the next iteration of the loop to fail. Commented Nov 3, 2016 at 19:11

1 Answer 1

3

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/

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

8 Comments

Now I get: , apple, banana. Why is there "," in the beginning
You can add some logic to prevent adding the comma the first iteration. If you follow the logic now though you can see that every iteration it's adding ", " + value. So it makes sense that there will be a comma in front.
I added a simple if statement to check if it's the first iteration. If it is we don't add the comma
Ok Thank You. Now if I try to access allData outside of the for loop... allData is the last value. eg array[10]... not cumulative of all values.. I need that cumulative value outside of the loop too
You should be able to use it out of the loop. Are you using += ?
|

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.