JavaScript新手求助:判断数组中是否存在指定数字的代码返回异常排查
Hey there! Let's break down what's going wrong with your code and fix it step by step.
First, let's look at your original code again for clarity:
const numberList = [1, 2, 3, 4]; function includes(arrays, searchElement) { for (let elements of arrays) { if (elements === searchElement) { return true; } else { return false; } } } console.log(includes(numberList, 3))
The Core Issue
The problem is in your loop logic: you're returning false the very first time an element doesn't match your search value.
When you call includes(numberList, 3), the loop starts with the first element (1). Since 1 !== 3, your else branch runs and returns false immediately—your function stops right here, never checking the second (2), third (3), or fourth (4) elements. That's why you're getting an incorrect false instead of the expected true.
The Fix
You only want to return false after checking every element in the array and finding no matches. Move the return false outside of the loop, like this:
const numberList = [1, 2, 3, 4]; function includes(arrays, searchElement) { for (let elements of arrays) { if (elements === searchElement) { // Found a match? Return true right away return true; } } // If we made it through the whole loop with no matches, return false return false; } console.log(includes(numberList, 3)) // Now logs true! console.log(includes(numberList, 5)) // Logs false, which is correct
How This Works
- The loop iterates through every element in the array.
- As soon as it finds an element that matches
searchElement, it returnstrueand exits the function. - If the loop finishes without finding any matches, the code moves to the line after the loop and returns
false.
This way, your function properly checks all elements before deciding the value isn't present.
内容的提问来源于stack exchange,提问作者Kiran

