为什么在循环中只检查一个值后函数返回false [英] Why does function return false after checking only one value in loop

查看:39
本文介绍了为什么在循环中只检查一个值后函数返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图检查数组中是否存在一个值,但我的嵌套 if 语句正在返回即使该值存在于数组中,也为 false.这一直有效,直到我在循环中添加了 else,现在它仅在要检查的值是第一个索引时才有效.

Trying to check if a value exists within an array, but my nested if statement is returning false even if the value exists in the array. This worked until I added an else to my loop, now it only works if the value to check for is the first index.

var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var inp = parseInt(prompt("Enter a number to see if it is in the array:"));

function checkIfInArray(n, anArray) {

  for (var i = 0; i < anArray.length; i++) {
    if (num[i] == n) {
      return true;
    } else {
      return false;
    }
  }
}

console.log(checkIfInArray(inp, num));

推荐答案

即使您在 for-loop 内进行了检查,for-loop 内的代码只运行一次,因为现在你已经添加了一个 else,它总是会返回一些东西.

Even though you have the check inside the for-loop, the code inside the for-loop runs only once because now that you've added an else, it will ALWAYS return something.

如果什么都没有找到,则返回 false 的正确方法是在 for 循环完成后添加 return false.

The correct way to return false if nothing was found, would be to add the return false after the for-loop finishes.

for(var i = 0;i < anArray.length;i++)
{
     if(num[i] == n)
     {
          return true;
     }
} 

return false;

这篇关于为什么在循环中只检查一个值后函数返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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