本篇文章给大家带来的内容是关于JavaScript中循环知识的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
for 循环
在脚本的运行次数已确定的情况下使用 for 循环。
语法:
for (变量=开始值;变量<h3>实例:</h3><p>解释:下面的例子定义了一个循环程序,这个程序中 i 的起始值为 0。每执行一次循环,i 的值就会累加一次 1,循环会一直运行下去,直到 i 等于 10 为止。</p><p>注释:步进值可以为负。如果步进值为负,需要调整 for 声明中的比较运算符。</p><pre class="brush:js;toolbar:false;">
<script>
var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>结果:
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
while 循环
while 循环用于在指定条件为 true 时循环执行代码。
用于 inference.sh 的 JavaScript/TypeScript SDK,可运行 AI 应用、构建代理、集成 150+ 模型。包名:@inferencesh/sdk(npm install),完整 TypeScript 支持。
语法:
while
(变量<p><strong>注意:除了</strong></p><h3>实例:</h3><p>解释:下面的例子定义了一个循环程序,这个循环程序的参数 i 的起始值为 0。该程序会反复运行,直到 i 大于 10 为止。每次运行i的值会增加 1。</p><pre class="brush:js;toolbar:false;">
<script>
var i=0
while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
</script>结果:
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
do...while 循环
do...while 循环是 while 循环的变种。该循环程序在初次运行时会首先执行一遍其中的代码,然后当指定的条件为 true 时,它会继续这个循环。所以可以这么说,do...while 循环为执行至少一遍其中的代码,即使条件为 false,因为其中的代码执行后才会进行条件验证。
语法:
do
{
需执行的代码
}
while
(变量<h3>实例:</h3><pre class="brush:js;toolbar:false;">
<script>
var i=0
do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0)
</script>结果:
The number is 0
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南









