简体   繁体   中英

Why does this function return only true, since there is no else statement to make it return false under a non true condition?

It seems to me that this bit of code is asking the function to return false regardless of what is internally going on. I only know to use else statements to return false values, but maybe there is something behind the scenes that I am not seeing that someone else could explain?

Challenge: Create a function that takes two arguments, an array of numbers (arr) and a number value (n). All you need to do is check whether the provided array contains the number value (n) or not. Return true if the array contains the value, false if not.

 function isItThere(arr, n) { for (var i = 0; i < arr.length; i++) { if (arr[i] === n) { return 'true'; } } return 'false'; } console.log(isItThere([1,3,5,6,7,8,9], 3));

The return 'false' statement is executed only after the array is exhausted and the element is not found.

 function isItThere(arr, n) { for (var i = 0; i < arr.length; i++) { if (arr[i] === n) { return 'true'; } } return 'false';//after the array search is done and not found } console.log(isItThere([1,3,5,6,7,8,9], 3)); console.log(isItThere([1,3,5,6,7,8,9], 100));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM