Pea*_*key 1 javascript for-loop
请原谅我的n00bness,因为我是Javascript和循环世界的新手,但我不知道如何最好地for loops在javascript中接近.希望理解for loops将有助于揭示其他类型的循环.
示例代码
for (var i=0; i < 10; i=i+1) {
document.write("This is number " + i);
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,当i初始化时,它从值0开始,然后根据条件进行评估< 10.如果它小于10,它执行该语句document.write("This is number + i);一旦它执行上述语句,才把它递增1的下一个值.
我咨询过的指南;
现在,http: //www.functionx.com/javascript/Lesson11.htm上的指南似乎另有说明了
要执行此循环,将检查"启动"条件.这通常是计数应该开始的初始值.接下来,测试条件; 此测试确定循环是否应继续.如果测试呈现真实结果,则表达式用于修改循环并执行Statement.执行Statement后,循环重新开始.
抛出我的那条线是If the test renders a true result, then the Expression is used to modify the loop and the Statement is executed.似乎推断因为0小于10,所以修改增量表达式,其将是0 + 1,然后document.write执行该语句.
我的问题
解释for循环的正确方法是什么?我自己的理解是否正确?同样的理解是否适用于其他编程语言,例如PHP,Perl,Python等?
想象一下for循环如下
for(initializers; condition; postexec) {
execution
}
Run Code Online (Sandbox Code Playgroud)
首次启动循环时,将var i = 0运行代码.这将初始化您将在循环内测试的变量
接下来,循环计算i < 10表达式.这将返回一个布尔值,该值在运行的前10次为真.当此表达式持续评估为true时,循环内的代码将运行.
document.write("This is number " + i);
每次运行此代码后,i++都会执行循环的最后一部分.此示例中的此代码在i每次执行后添加1 .
在执行该代码之后,检查循环的条件并重复步骤2和3,直到最后条件为假,在这种情况下退出循环.
这种循环方式适用于您提到的语言.
让我们看一下ECMAScript 规范中的相应部分:
产生式
IterationStatement :for ( varVariableDeclarationListNoIn;Expression opt;Expression opt)Statement
的计算如下:Run Code Online (Sandbox Code Playgroud)1. Evaluate VariableDeclarationListNoIn. 2. Let V = empty. 3. Repeat a. If the first Expression is present, then i. Let testExprRef be the result of evaluating the first Expression. ii. If ToBoolean(GetValue(testExprRef)) is false, return (normal, V, empty). b. Let stmt be the result of evaluating Statement. ... f. If the second Expression is present, then i. Let incExprRef be the result of evaluating the second Expression. ii. Call GetValue(incExprRef). (This value is not used.)
正如您所看到的,在步骤 1 中,对变量赋值进行了评估。在步骤 3a 中,测试条件。在步骤 3b 中,计算循环体,然后在步骤 3f 中计算第三个表达式。
因此你对for循环的理解是正确的。
假设它在其他语言中的工作方式相同,因为for循环是编程语言中非常常见的语句(请注意,Python 没有这样的语句)。但如果你想绝对确定,你最好也查阅他们的规格。
| 归档时间: |
|
| 查看次数: |
2659 次 |
| 最近记录: |