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

查看:121
本文介绍了为什么仅在循环中检查一个值后函数返回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循环中进行了检查,但for循环中的代码仅运行了一次,因为现在您已经添加了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天全站免登陆