I was just wondering if I could get some guidance on an issue I am having with nested for loops in javascript.
I currently have the following nested for loop in place
for (var i = 0; i <= score; i++)
{
for (var j = 0; j <= i; j++)
{
var stsc = '<img src="./images/star.png"/>';
}
}
The aim is to get the variable stsc to show the number of stars depending on the count of the score variable.
Currently, it will only show 1 star no matter what the value of score is. I have tried adding stsc outside of the nested loop to no avail. No matter what I do it will show nothing other than 1 star.
Could you point me in the right direction as to how to get it to show the correct number of stars (3 stars if score is 3, 0 stars if score is 0 etc...)
Thanks everyone
3 Answers 3
var stsc="";
var score=0;
for (var i = 1; i <= score; i++)
{
stsc = stsc +'<img src="./images/star.png"/>';
}
2 Comments
You just need a normal for
loop and string concatenation:
var stsc = '';
for (var i = 0; i < score; i++) {
stsc += '<img src="./images/star.png"/>';
}
Think about it like this: You want to create n
stars, where n
is the value of the score. Hence you have to repeat the process of creating the HTML string n
times. That's what a for
loop is doing, repeating something until a condition is fulfilled. And instead of overwriting the variable in each iteration, you have to add to it.
3 Comments
score
is defined. Have a look at the console for errors.for
loop correctly and specifically that "i" is being incremented properly.You don't need any for
loops:
var stsc = score === 0 ? "" : new Array(score + 1).join("<img src=./images/star.png>");
0
toscore
should just do fine. Learn about string concatenation: developer.mozilla.org/en-US/docs/JavaScript/Guide/….stsc
, over and over, and not doing anything with it.