简体   繁体   中英

Javascript conditional statement not executing

I'm attempting to make a function that builds a checker board however I can't get my second conditional statement to execute and create a new line.

 function grid(size) { var board = ""; for (i = 0; i <= (size * size); i++) { if (i % 2 === 0) { board += ' '; } else if (i % size === 0) { board += "\\n"; } else { board += '#'; } } console.log(board); } grid(8); 

It appears the else if statement is not executing because I've tried changing the '\\n' and condition to other things but nothing is printed. This question is from Eloquent Javascript and the given solution is this:

 var size = 8; var board = ""; for (var y = 0; y < size; y++) { for (var x = 0; x < size; x++) { if ((x + y) % 2 == 0) board += " "; else board += "#"; } board += "\\n"; } console.log(board); 

I'm not sure why the second one works but mine doesn't.

i % 2 will always execute instead of i % (8 * 8) . You should swap their order or remove the else from the second if .

Let´s analyse your code:

 if(i % size === 0)

This means, when i is equal to 0 or is a multiple of size. In your case, size is 8.

So for your if to trigger, i should be 0,8,16,32....

In all this cases, it will never fire because when i is 0,8,16,32... i % 2 is 0, so it will run the first if instead and never the second one. You should inverse the order of the ifs or run both

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