vzupo vzupo - 3 months ago 9
jQuery Question

how can i simplify a loop

Here is a for loop. I am trying to simplify(as in downgrade and take it out the loop(s) for ease of use).
Not sure how to--can someone explain.

if (myBox.length >= i) {
var smile = '';
for (var x = 0; x < myBox[i].myRating; x++) {
smile = smile + '<span>☺</span>';
}
$('#table').append('<tr><td>' + myBox[i].Title + smile + '</td><tr>');
}

Answer

if you want to downgrade, you need to start from the biggest value and run loop to '0'. If you wrote correctly, I presume the code will be like this

if (myBox.length >= i) {
var smile = '';
for (var x = myBox[i].myRating; x > 0; x--){
  smile = smile + '<span>☺</span>';
}

here's another sample for downgrade

for(var x=5; x>0; x--){
  console.log(x + ',');  //it'll print 5,4,3,2,1, in your console log
  //if you want to print 0 also, just use "x>=0" in the for loop
}

And please post full code always