简体   繁体   中英

Loop issue from Elegant javascript Chapter 2 Exercise 3

This question comes from the above source, in which I'm asked to make a chess board. The provided solution uses the same method, except y < size and x < size. But why doesn't this way work?


var size = 8;
var chess = "";

for (var y = 0; y == size; y++){
    for (var x = 0; x == size; x++){

        if ((x + y) % 2 == 0)
            chess += " ";
        else
            chess += "#";

    }
    chess += "\n";    
}

console.log(chess);

--

You need to understand how the for loop works. Read up on it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for .

The second clause is a condition which is checked each time through the loop, including at the very beginning. If it is false , then the loop is exited. The loop continues while it is true . In your case, you want to keep looping until x or y has reached the size of the board (actually, the size of the board less 1, since we are starting at 0). Therefore, the following is correct:

for (var y = 0; y < size; y++) {
                ^^^^^^^^

If you do what you did, and say

for (var y = 0; y == size; y++){
                ^^^^^^^^^

then the loop will never execute at all . It will start off with an x of zero, then check if that is equal to size which it is not ( 0 !== 8 ), and therefore exit the loop without even executing it once.

Since x and y value change, the conditions for for loops should be < .

This should work:

var size = 8;
var chess = "";

for (var y = 0; y < size; y++){

    for (var x = 0; x < size; x++){

        if ((x + y) % 2 == 0)
            chess += " ";
        else
            chess += "#";
    }

    chess += "\n";    
}

console.log(chess);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM