Pad*_*wan 2 javascript for-loop function while-loop
我不明白为什么这个函数作为一个While循环,但不是一个For-Loop.我试图计数到10并在每次迭代时打印到控制台.
while循环:
function oneToTenW() {
var x = 0;
while(x < 10) {
x++;
console.log ("x is equal to " + x);
}
}
Run Code Online (Sandbox Code Playgroud)
for循环:
function oneToTenF() {
for(var x = 0; x < 10; x++);
console.log ("x is equal to " + x);
}
Run Code Online (Sandbox Code Playgroud)
当我调用While-Loop时,我得到了这个:
oneToTen();
x is equal to 1
x is equal to 2
x is equal to 3
x is equal to 4
x is equal to 5
x is equal to 6
x is equal to 7
x is equal to 8
x is equal to 9
x is equal to 10
Run Code Online (Sandbox Code Playgroud)
而当我调用For-Loop时,我得到了这个:
oneToTenf();
x is equal to 10
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
这一行就在这里:
for(var x = 0; x < 10; x++);
Run Code Online (Sandbox Code Playgroud)
因为最后有一个分号,所以语句在那里有效地终止,循环执行而不做任何事情.要让循环执行它下面的语句,你需要通过删除分号在循环体中包含该语句:
for(var x = 0; x < 10; x++)
console.log ("x is equal to " + x); // <- the line immediately after the for statement will be executed on every iteration
Run Code Online (Sandbox Code Playgroud)
或者通过将要执行的语句(括号)括起来:
for(var x = 0; x < 10; x++) {
console.log ("x is equal to " + x);
}
Run Code Online (Sandbox Code Playgroud)
现在,每次循环迭代时都会执行该语句.
因为你有一个额外的分号
function oneToTenF() {
for(var x = 0; x < 10; x++);
// Here -------------------^
console.log ("x is equal to " + x);
}
Run Code Online (Sandbox Code Playgroud)
所以循环体完全由空语句(;
)组成.当它完成,然后将console.log
线运行,显示的电流值x
,这是现在10
.
要将console.log
线放在循环体中,从技术上讲,您只需要删除;
:
function oneToTenF() {
for(var x = 0; x < 10; x++)
console.log ("x is equal to " + x);
}
Run Code Online (Sandbox Code Playgroud)
...虽然我总是{}
在控制结构上使用block():
function oneToTenF() {
for(var x = 0; x < 10; x++) {
console.log ("x is equal to " + x);
}
}
Run Code Online (Sandbox Code Playgroud)
无论是那些会告诉你的价值观0
通过9
,因为一个for
循环是这样的:
x = 0
)x++
)x < 10
)