JavaScript for 循环问题
for循环可以重复一个数字3次吗?例如,
for (i=0;i<=5;i++)
创建:1,2,3,4,5。 我想创建一个执行此操作的循环: 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5
这可能吗?
Is it possible for a for-loop to repeat a number 3 times? For instance,
for (i=0;i<=5;i++)
creates this: 1,2,3,4,5.
I want to create a loop that does this: 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5
Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
是的,只需将循环包装在另一个循环中即可:(
您的原始代码说您想要 1-5,但您从 0 开始。我的示例从 1 开始)
Yes, just wrap your loop in another one:
(Your original code says you want 1-5, but you start at 0. My example starts at 1)
for 循环中可以有两个变量,并且仅当 j 是 3 的倍数时才增加 i:
for (i=1, j=0; i <= 5; i = ++j % 3 != 0 ? i :我+1)
You can have two variables in the for loop and increase i only when j is a multiple of 3:
for (i=1, j=0; i <= 5; i = ++j % 3 != 0 ? i : i + 1)
确实。您可以嵌套 for 循环:
请注意,问题中的代码将打印
0, 1, 2, 3, 4, 5
,而不是1, 2, 3, 4, 5
>。我已修复该问题以符合您在我的答案中的描述。Definitely. You can nest for loops:
Note that the code in your question will print
0, 1, 2, 3, 4, 5
, not1, 2, 3, 4, 5
. I have fixed that to match your description in my answer.只需添加嵌套在第一个循环中的第二个循环:
Just add a second loop nested in the first:
您可以使用嵌套的 for 循环
You can use nested for loops
您可以在循环中使用两个变量:
但是,通过查看代码,它的作用并不那么明显。您最好将一个循环嵌套在另一个循环中:
You can use two variables in the loop:
However, it's not so obvious by looking at the code what it does. You might be better off simply nesting a loop inside another:
我看到很多带有嵌套循环的答案(显然是最好、最容易理解的解决方案),然后是一些带有一个循环和两个变量的答案,尽管令人惊讶的是没有人提出单个循环和单个变量。所以只是为了练习:
I see lots of answers with nested loops (obviously the nicest and most understandable solution), and then some answers with one loop and two variables, although surprisingly nobody proposed a single loop and a single variable. So just for the exercise:
如果您确实只想要一个循环,则可以使用第二个变量,例如:
尽管,根据您想要此的原因,可能有更好的方法。
You could use a second variable if you really only wanted one loop, like:
Although, depending on the reason you want this, there's probably a better way.