JavaScript 中的 While 循环 vs. For 循环? [英] While Loops vs. For Loops in JavaScript?

查看:35
本文介绍了JavaScript 中的 While 循环 vs. For 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for 循环上使用 while 循环有什么好处?当我遍历数组时,我总是使用 for 循环,所以我想知道我是否在这里遗漏了什么.

What are the benefits of using a while loop over a for loop? When I'm iterating through arrays, I always use a for loop so I wondered if I'm missing something here.

我从来没有遇到过 for 循环不起作用的情况,但我担心我可能会在这里养成坏习惯.我对循环的使用涉及网页上的元素、动画中的内容等.

I've never had a situation where a for loop doesn't do the job, but I'm worried that I may be picking up bad habits here. My usage of loops has been with regards to elements on web pages, stuff in animations, etc..

推荐答案

以下是我选择其中一个的原因:

These are the reasons I would choose one over the other:

For 循环语法:

for( int i = 0; i > 10; i++)
{
    //Some code here
}

我会使用 for 循环,因为我可能知道我需要做的迭代次数,而且我有一个有时会很方便的 INCREMENTING 变量.

I would use a for loop for the reason that I may KNOW the NUMBER OF ITERATIONS I need to do and I have an INCREMENTING variable which can be handy sometimes.

While 循环语法:

While-loop Syntax:

while(!done)
{
    //Some code goes here
}

当我不确定可能需要执行多少次迭代时,我会使用这个循环.示例:等待用户输入正确的输入值并不断循环直到他/她输入正确的值.

I would use this loop when I am NOT SURE how many ITERATIONS I might need to carry out. Examples: Waiting for user to input correct input values and keep looping until he/she inputs the proper value.

Do-While 循环语法:

Do-While loop Syntax:

do
{
    //Some code here
}
while(!done);

这个循环几乎和 while 循环一样,但是当我需要做一些事情至少一次时我更喜欢这个,然后我开始验证它是什么会让我想要循环并再次执行该代码.示例:第一次询问用户输入,然后验证它.如果输入错误,则循环返回并再次要求输入

This loop is almost the same as a while-loop but I would prefer this when I need something done ATLEAST ONCE before I start verifying whatever it is that would make me wanna loop and do that code again. Example: ask a user for an input for the first time and then validate it. If wrong input given then loop back and ask for input again

这篇关于JavaScript 中的 While 循环 vs. For 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆