热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

if-else语句嵌套在while循环中-if-elsestatementnestedinwhile-loops

IamabeginnerwhenitcomestoJavascript.IamnotreallysurewheretoaskappropriatelyandIt

I am a beginner when it comes to Javascript. I am not really sure where to ask appropriately and I thought since I've been stalking Stack Overflow for awhile now, this might be the right time to finally make an account and start my profile here. The book I am reading doesn't really have a Help Forum of any sort.

谈到Javascript,我是初学者。我不确定在哪里提出适当的问题,因为我现在一直在跟踪Stack Overflow一段时间,这可能是最终建立帐户并在这里开始我的个人资料的最佳时机。我正在阅读的这本书并没有任何形式的帮助论坛。

Anyways, I am reading a book that is in tandem with some JS exercise and I wanted to try combining principles of while-loops that contain nested if..else statements. My code is below :

无论如何,我正在阅读一本与JS练习相关的书,我想尝试结合包含嵌套if..else语句的while循环原理。我的代码如下:

var teams = ["Chiefs", "Bees", "Tigers", "Bears"];
var i = 0;
while (i 

The exercise was only suppose to be using the concept of while and if but obviously with my curiosity into programming I wanted to add the else statement but I cannot get the code to work. The only instance I got the code to work properly was without the else statement.

练习只是假设使用while和if的概念,但显然我对编程的好奇心,我想添加else语句,但我无法让代码工作。我让代码正常工作的唯一实例是没有else语句。

My main goal/curiosity is I would like it to alert "Query not found!" when the if statement can't find the string in the array, in this case I've written "Lions".

我的主要目标/好奇心是我希望它提醒“查询未找到!”当if语句找不到数组中的字符串时,在这种情况下我写了“Lions”。

Thank you for your help in advance!

提前谢谢你的帮助!

3 个解决方案

#1


0  

You can decide whether something is found when you find it. But you can only decide something is not found when you've looked at everything, which should be outside the loop.

您可以在找到时确定是否找到了某些内容。但是当你看到所有东西时,你只能决定找不到的东西,这应该在循环之外。

var teams = ["Chiefs", "Bees", "Tigers", "Bears"];
var i = 0, position = null;
while (i 

#2


0  

You need to remove the 'break;' from the else loop. That break is going to terminate your while loop on the first iteration (when i is 0) when it doesn't find "Tigers".

你需要删除'break;'来自else循环。当它没有找到“Tigers”时,那个中断将在第一次迭代(当我为0时)终止你的while循环。

break's apply to looping constructs, not if/elses. I'm guessing you thought it would break/end the else block, but its actually breaking out of the while loop.

break适用于循环结构,而不是if / elses。我猜你认为它会破坏/结束else块,但它实际上是打破了while循环。

#3


0  

No need for breaks, but you can still leave one in the if to end the loop:

不需要中断,但你仍然可以在if中结束循环:

Working Example

 var teams = ["Chiefs", "Bees", "Tigers", "Bears"];
 var i = 0;
 while (i 

推荐阅读
author-avatar
苏小丫123_877
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有