JSFiddle - React, Tailwind, and code Playground
by orolo
JavaScript
/*
3. Using a for loop (not a for-in loop.) Print 0 to 9 comma delineated no spaces. Output will be 0,1,2,3,4,5,6,7,8,9,
Fool around until it runs without error and produces proper output; not 1 too many or 1 too little.
*/
document.write('3. ');
for (i = 0; i <= 9; i++) {
document.write(i + ',');
}
/*
4. Modify your previous loop:
Output the number prefixed with "count=" and suffix that with a comma. The trailing comma must be missing this time - use an if() statement to avoid the last comma; after you get it follow thru the code instead of just stopping because it worked- sadly, your brain might come away remembering the mistake you spent time on instead of the solution you stumbled upon (so, put in the time to know why you got it right.)
The output looks like this: count=0,count=1,count=2,count=3,count=4,count=5,count=6,count=7,count=8,count=9
again, this is a code fragment, as each enumerated item here is, so paste it into your text file.
*/
document.write('<br>4. ');
for (i = 0; i <= 9; i++) {
if (i === 9) {
document.write('count=' + i);
}
else document.write('count=' + i + ',')
}
//^ this can be re-factored, I'm sure. I'll come back to it.
/*
5. New for loop:
output this: 4,6,8,10,
There are two main ways to output this - try to do both of them. Hint: one uses an if() with modulus and the other faster one only changes the iterator variable.
*/
document.write('<br>5a. ');
for (i = 2; i <= 10; i += 2) {
document.write(i + ',');
}
document.write('<br>5b. ');
for (var i = 1; i <= 10; i++) {
if ((i % 2) == 0) {
document.write(i + ',');
}
}
/*
6. New for loop:
output this: 5,4,3,2,1,fire!,-1,-2,missed!
Only use 1 for loop to do this.
*/
document.write('<br>6. ');
for (i = 5; i >= -3; i--) {
if (i == 0) {
document.write('fire!')
}
else if (i == -3) {
document.write('missed!')
}
else {
document.write(i + ',')
}
}
/*
7. new for loop for an array (for loop are...