简体   繁体   中英

Trying to Understand this JavaScript For Loop with Ternary Operator

var res = '\n', i, j;
for (i = 1; i <= 7; i++) {                
    for (j = 1; j <= 15; j++) {
        res += (i * j) % 8 ? ' ' : '*';
    }
    res += '\n';
}
alert(res);

(Copy / Pasted from Object-Oriented JavaScript - Third Edition, Ved Antani, Stoyan Stefanov)

Trying to understand this loop. I understand what's happening but not why.

res += (i * j) % 8 ? ' ' : '*';

I'm reading the ternary operator as follows.

  • boolean expression: (i * j) % 8
  • execute if true: concatenate space with res
  • execute if false: concatenate asterisk with res

On the first iteration, when it comes to the inner loop, it only outputs '*', when the modulo is 0, all other times it outputs ' '.

Why does it do this?

Also, don't understand the first line. What is the following doing?

var res = '\n', i, j;  

What is the purpose of assigning the variable res to 3 values.

In the console it works fine without this line.

var res = '\n', i, j;  

These are three vars, written down in a confusing way:

var res = '\n'; // newline
var i;
var j;

In one line:

var i, j, res = '\n';  

The script runs OK. I replaced the space with a dash, this is the result:

-------*-------
---*---*---*---
-------*-------
-*-*-*-*-*-*-*-
-------*-------
---*---*---*---
-------*-------

If i=1 , j=i , then i*j%8 is not 0, thus true, which results in a dash. First line, you see seven dashes, then a *, etc.

It's running all the multiplications from 1*1 to 1*14 all the way to 6*1 to 6*14. As you already pointed out only if the modulo of said multiplication is zero it's adding a * to the res string. In the range of 1 to 14 the only time this is true is for 8.

You could add something to your inner block to visualize and aid you with understanding. An example would be:

console.log("i:", i, " j:", j, " multiplication:", i*j, "mod8:", (i*j)%8)

As a complete example this would look like this:

var res = '\n', i, j;
for (i = 1; i <= 7; i++) {                
    for (j = 1; j <= 15; j++) {
        res += (i * j) % 8 ? ' ' : '*';
        console.log("i:", i, " j:", j, " multiplication:", i*j, "mod8:", (i*j)%8)
    }
    res += '\n';
}
alert(res);

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