繁体   English   中英

使用if语句的for循环不遍历整个数组

[英]For loop with if statement not iterating over entire array

我很尴尬地问这个基本问题。 但是,如果这是我的js知识中的根本性或简单性鸿沟,我宁愿得到一个解释,为什么我可以早日而不是稍后开始养成良好的习惯。

我有一个函数,将字符串作为参数并将其与数组值进行比较。

function validateHello(greetings){
var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc'];
  for(var i = 0; i < hello.length; i++){
    if(greetings === hello[i]){ 
      return true;
    }else{ 
      return false;
    }

   }

}

似乎每次我运行此for循环时,它仅检查第一个数组hello[0] ,然后似乎中断。 我该如何阻止这种情况的发生? 我尝试使用continue; 返回true后,但这也无法解决。 我觉得我应该知道这一点,但是我完全是在脑子虚弱,无法弄清楚为什么。 谢谢!

因为您的return false语句,您应该将其放在循环之外并删除else语句:

function validateHello(greetings){
var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc'];
  for(var i = 0; i < hello.length; i++){
    if(greetings === hello[i]){ 
      return true;
    }
  }
  return false;
}

说明:当greetings参数不等于第一个元素'hello' ,代码将执行else语句,该语句返回false并停止函数执行。

您的return语句脱离了该功能。 如果删除return语句,它将遍历整个数组(尽管看起来您实际上并没有做任何事情,所以我不知道您怎么知道)。

如果您只想在数组中添加greetings返回true,那么这就是您要查找的内容:

function validateHello(greetings){
var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc'];
  for(var i = 0; i < hello.length; i++){
    if(greetings === hello[i]){ 
      return true;
    } 
   }
    return false;
}

请注意,返回false已移至循环外部。 这样,一旦找到greetings ,它将返回true,否则它将完成循环,然后返回false。

我在代码中添加了注释,并更改了错误的部分。 删除else块,并将return false; 退出for循环。 这将形成一个完整的for循环。 只有if语句为true的条件, for循环才会return 如果for循环结束且没有返回值,则return false;否则, return false; 下面的语句将被执行。

function validateHello(greetings){
    var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc'];
    for(var i = 0; i < hello.length; i++){
        if(greetings === hello[i]){ 
            return true;
        }
        /* if you add a else block here. it means you want your 'else condition' to be checked in every single loop. Since 'if statement has a 'return' and 'else' statement has a 'return'. So if there is a 'else' here, no matter what condition you add , your for loop can only be executed once.  */
    }
    return false; // only the for loop is over and no return. this statement will be executed.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM