Loop issue from Elegant javascript Chapter 2 Exercise 3 -
this question comes above source, in i'm asked make chess board. provided solution uses same method, except y < size , x < size. why doesn't way work?
var size = 8; var chess = ""; (var y = 0; y == size; y++){ (var x = 0; x == size; x++){ if ((x + y) % 2 == 0) chess += " "; else chess += "#"; } chess += "\n"; } console.log(chess);
--
you need understand how for
loop works. read on @ https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/for.
the second clause condition checked each time through loop, including @ beginning. if false, loop exited. loop continues while true. in case, want keep looping until x
or y
has reached size of board (actually, size of board less 1, since starting @ 0). therefore, following is correct:
for (var y = 0; y < size; y++) { ^^^^^^^^
if did, , say
for (var y = 0; y == size; y++){ ^^^^^^^^^
then loop never execute @ all. start off x
of zero, check if equal size
not (0 !== 8
), , therefore exit loop without executing once.
Comments
Post a Comment