Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through numbered variables in javascript [duplicate]

I have data that is being returned from a JQuery .ajax function as an array.

Now the fields in that array are named & numbered i.e part1, part2, part3, etc.

I have some code below that I thought may loop through it but it returns NaN.

for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0].part + a) + '</div>';
}

I couldn't get any of the sugegstions to work so I did this instead.

var h = new Array();
h[1] = exploded[0].part_1;
h[2] = exploded[0].part_2;
h[3] = exploded[0].part_3;
h[4] = exploded[0].part_4;
h[5] = exploded[0].part_5;
h[6] = exploded[0].part_6;
h[7] = exploded[0].part_7;
h[8] = exploded[0].part_8;
h[9] = exploded[0].part_9;

I know it is a bit long winded but when I am dealing with multiple songs also I can loop them all with the array keys.

like image 891
Matt Bridges Avatar asked Apr 28 '26 17:04

Matt Bridges


1 Answers

Try it this way:

for (var a = 1; a <= 9; a++) {
    newtext += '<div class="part">' + (exploded[0]['part_' + a]) + '</div>';
}
like image 140
Nikko Reyes Avatar answered Apr 30 '26 06:04

Nikko Reyes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!