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
121 views
in Technique[技术] by (71.8m points)

javascript - Creating a function to go through an array and if it finds a specific numeric value it returns true

I'm creating a function to sort through an array to return a boolean indicating whether or not the number 7 is anywhere in the array.

Reading my code out loud I feel like it should do exactly what I am asking it to do. Although I fully realize I am a beginner and I'm going to make mistakes. I cannot figure this one out.

If I input includesSeven([1, 7, 8, 10]); this should return true, however I am getting false as my return

function includesSeven(array) {
  for (var i = 0; i <= array.length; i++) {
    if (array[i] === 7) {
      return true;
    } else {
      return false;
    }
  };
};

EDIT: I do apologize for the image and not the code.

My code for this:
enter image description here

question from:https://stackoverflow.com/questions/65947769/creating-a-function-to-go-through-an-array-and-if-it-finds-a-specific-numeric-va

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

1 Reply

0 votes
by (71.8m points)
function includesSeven(array){
    for(var i = 0; i < array.length; i++){
        if(array[i] == 7){
            return true;
        }
    }
    return false;

}

in your original code, you were essentially just checking the first number in the array, you should return false after the for loop has completed.

while iterating through the array, if it finds the number 7, itll return true. once its all completed, its safe to assume that the number 7 isnt in the array, so you can just return false.


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

...