陷入了无限循环
请帮忙 在这里,我想在控制台中打印所有数组元素,条件是它们不是数字,并且不是从字母“ a”开始的,
我认为问题是将i += 1放在哪里; 但是实际上,当我改变其位置时,输出不是我需要的。
我试图做到这一点,一切都可以,但是我不知道有什么问题。
这是代码:
let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let i = 0;
while (i < friends.length) {
if (friends[i][0] === "A" || typeof friends[i] === "number") {
continue;
}
console.log(friends[i]);
i += 1;
}
我试图使用以前说过的事情
Please help
here I wanna print in the console all array elements in condition that they are not numbers and they do not start with letter "A"
I think the problem is where to put the i += 1;
but actually when I am changing its position the output is not what like I need.
I tried to do it with for and every thing turned out okay, but I don't know what is the problem with while.
Here is the code:
let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let i = 0;
while (i < friends.length) {
if (friends[i][0] === "A" || typeof friends[i] === "number") {
continue;
}
console.log(friends[i]);
i += 1;
}
I tried to use while to do what I've said previously
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于您已经有一个数组,因此更好的方法就是循环通过它。
这样,您可以完全避免
完全循环。
文档您获得无限循环的原因是因为
继续
语句 IN 。这会跳过该迭代的其余代码,i += 1
不会被执行。Since you already have an array, a better approach for this would be to just loop through it.
That way you could avoid
while
loop entirely.documentation for filter()
The reason you were getting an infinite loop is because of the
continue
statement insideif
. That skips the rest of the code for that iteration andi += 1
doesn't get executed.当您
继续
时,您不会增加i
,因此在下一次迭代中i
保持不变。您始终可以使用
for ... of
无需手动递增i
When you
continue
, you do not incrementi
, so in next iterationi
stays the same.You can always use
for ... of
to drop need for manually incrementingi
您需要每次循环循环时都会增加
i
,或者您的情况永远无法解决(除非所有人都符合您的状况)。*我改变了寻找所需结果而不是负面的条件(只是个人喜好)。
You need to increase
i
every time you loop or your while condition will never resolve (unless all meet your condition).*I changed the condition to look for the desired result rather than the negative (just a personal preference).
请参阅代码的更改。这将按预期工作。
Please see the changes in code.This will work as expected.
该代码进入无限循环,因为它不会将I变量递增在IF内部和继续之前。
您的代码可以像这样很容易修复
The code enters into an infinite loop because it won´t increment the i variable inside the if and before the continue.
Your code can be easily fixed like this
试试这个,希望对你有帮助
try this, hope this help you