[英]JavaScript For Loop - For fun, and probably simple
I've recently completed a challenge in Marjin Haverbeke's book, " Eloquent Javascript, Second Edition ". 我最近在Marjin Haverbeke的书“ Eloquent Javascript,第二版 ”中完成了一项挑战。
One had to create this console output using a for loop: 必须使用for循环创建此控制台输出:
#
##
###
####
#####
######
#######
The answer is this:
for (var i = '#'; i.length < 8; i += '#') {
console.log(i);
}
What I would like to know is why the first line is not two hashes ('##') as surely the updating section of the loop (i += '#') adds '#' to i (already = to '#'), therefor meaning that the first iteration of the loop should surely output '##'? 我想知道的是为什么第一行不是两个散列('##'),因为循环的更新部分(i + ='#')肯定会将'#'添加到i(已经=到'#' ),因此意味着循环的第一次迭代一定会输出'##'吗?
Perhaps I need a lesson on how this loop really works. 也许我需要一个关于此循环如何真正工作的课程。
Yours truly, still seemingly JS newbie. 您的真实,还是貌似JS新手。
for (init(); condition(); update()) {
body();
}
is equivalent to 相当于
init();
while (condition()) {
body();
update();
}
Thus, the first time i += '#'
runs is only after the first console.log(i)
(when i
was just '#'
). 因此,
i += '#'
的第一次运行仅在第一个console.log(i)
(当i
只是'#'
)。
@Callum you should first check how for loop works. @Callum,您应该首先检查for循环的工作方式。
if you have written . 如果你写过。
for (var i = '#'; i.length < 8; i += '#') {
console.log(i);
}
so what happen in this loop is this . 所以在这个循环中发生的是这个。
1 ) first var i ='#' initiallize
1)
first var i ='#' initiallize
then condition 然后条件
2) i.length < 8
2)
i.length < 8
then it goes to executed the statement 然后执行语句
3) console.log(i);
3)
console.log(i);
4) then increment
4)
then increment
i += '#'
then from step 2 to 4 然后从步骤2到4
this is what for loops algorithm works 这就是for循环算法的工作原理
it is just like post increment. The order of execution is:
--> initialisation
--> check condition
--> execute body
--> increment value
so first it would print the value then increment it.
This would give ##
in first row: 这将在第一行中显示
##
:
for (var i = '#'; i += '#',i.length < 8; ) {
console.log(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.