Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

javascript - Why does function return false after checking only one value in loop

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...