[英]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) (从面向对象的JavaScript复制/粘贴-第三版,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. 我正在阅读以下三元运算符。
(i * j) % 8
(i * j) % 8
res
res
连接 res
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 ' '. 在第一次迭代中,当涉及到内循环时,它仅输出“ *”,当模为0时,所有其他时间均输出“”。
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. 将变量
res
分配给3个值的目的是什么。
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. 如果
i=1
, j=i
,则i*j%8
不为0,因此为true,这导致破折号。 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. 它正在运行从1 * 1到1 * 14一直到6 * 1到6 * 14的所有乘法。 As you already pointed out only if the modulo of said multiplication is zero it's adding a
*
to the res
string. 正如您已经指出的那样,仅当所述乘法的模为零时,才在
res
字符串中添加*
。 In the range of 1 to 14 the only time this is true is for 8. 在1到14的范围内,唯一的正确时间是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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.