Chris
Chris

Reputation: 429

Nested For Loops - Javascript

I have a question that relates to the question I asked here

I am trying to nest a loop and not quite sure if it is the way to go. What I want to do is have a number of stars displayed relevant to the score. So, if they get 3 questions they get 3 stars. The bit I am having trouble with is displaying empty stars if they haven't reached the required score.

E.G: 10 required to get to the next level. They score 6. I can display 6 gold stars, but I am having trouble displaying 4 empty stars. I hope I explained this right.

This is the code I have so far

var se = '';
var sep = '';
for (var i = 1; i <= score; i++)
{
    se = se + '<img src="./images/star.png"/>'; 
}

I also have this loop for trying to display the empty stars

for (var j = 1; j <= i; j++)
{
    sep = sep + '<img src="./images/emptystar.png"/>';
}

I am not sure if this needs to go inside the for loop already there or outwith it. Also, for some reason it doesn't display the correct number of empty stars. It's displaying 1 empty for 0 correct answers and 3 or 4 for anything else

I think I have the right calculation in place in the second loop. Any pointers where I am going wrong would be much appreciated. As I said, the first loop works as it should.

Thanks everyone

Upvotes: 0

Views: 932

Answers (3)

Cerbrus
Cerbrus

Reputation: 72857

Try this:

var stars = '';
for (var i = 1; i <= 10; i++) {                        // Loop 10 times
    var empty = (i > score)?'empty':'';                // If i > score, set this variable to the string 'empty';
    stars += '<img src="./images/'+ empty +'star.png"/>'; // Add the image (star.png or emptystar.png depending on the score).
}

The advantage of this is that you only need 1 loop, meaning you're not duplicating any code.

For score == 6, this returns:

<img src="./images/star.png"/>
<img src="./images/star.png"/>
<img src="./images/star.png"/>
<img src="./images/star.png"/>
<img src="./images/star.png"/>
<img src="./images/star.png"/>
<img src="./images/emptystar.png"/>
<img src="./images/emptystar.png"/>
<img src="./images/emptystar.png"/>
<img src="./images/emptystar.png"/>

So, how does that line var empty = (i > score)?'empty':''; work, you're asking?
Simple, it's a ternary operator. Shorthand for:

var empty;
if(i > score){
    empty = 'empty';
}else{
    empty = '';
}

Upvotes: 3

mika
mika

Reputation: 1451

Just use one loop:

var score = 5;
var sep = "";
for (var i = 0; i <= 10; i++)
{
    sep += (i < score) ? '<img src="./images/star.png"/>' : '<img src="./images/emptystar.png"/>';
}

I didn't test but that should get you started.

Upvotes: 0

Tucker
Tucker

Reputation: 7362

try this:

var stars = '';
var maxstars = 10;

for (var i = 0; i < score; i++)
{
    stars = stars + '<img src="./images/star.png"/>'; 
}

for (var j = score; j < maxstars; j++)
{
    stars = stars + '<img src="./images/emptystar.png"/>';
}

Upvotes: 2

Related Questions