I'm new to JavaScript and may have asked a dumb question.. But the result returned from below code made me so confused. I'm not sure why only the first sentence show the value of i and it was in the last number of 3.
I'm also confused when the code document.write('<h1>' + i + msg + '<h1>') being executed, why it didn't just write the aggregated value of the variable 'msg'? The value of msg didn't get wiped out and it should contain both the 1st and 2nd value passed into it isn't it? This looks a bit confusing to me as I came with some python knowledge and it didn't work in the same way.
var scores = [24, 32, 47];
var scores = [24, 32, 47];
var scores = [24, 32, 47];
var arrayLength = scores.length;
var roundNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
roundNumber = i + 1;
msg += ' Round ' + roundNumber + ': ';
msg += scores[i] + '<br>';
}
document.write('<h1>' + i + msg + '<h1>')
Result returned from the html:
3 Round 1: 24
Round 2: 32
Round 3: 47
My expected result:
0 Round 1: 24
1 Round 2: 32
2 Round 3: 47
document.writeruns after the end of the loop.It does output all the aggregated content of
msg. That isn't the issue.The bit that's going wrong is the use of
i- you only use it once in the output, after the loop ends. Therefore what you see will only have the final value it had when the loop ended, hence it shows3, and does so once only.Unlike
msgwhich you are adding to each time the loop runs (because+=appends new content to the existing variable), the value ofiis overwritten with a new value each time the loop runs (that's what thei++in theforsyntax does).To make it do what you want you simply need to incorporate the
ivalue intomsgas you go along instead.P.S. I also simplified the code slightly - it's unclear why you declared the same
scoresarray 3 times with the same value, andarrayLengthandroundNumberdon't need to exist as separate variables, and certainly not ones which have scope outside the loop.ialso doesn't need scope outside the loop anymore.