我正在研究如何在javascript函数中实现二进制搜索,结果发现当我返回该值并将其保存到变量中时,然后在我进行console.log时,这是未定义的。
const recursiveBinarySearch = (numbers, target) => {
const midpoint = Math.floor(numbers.length / 2);
if (numbers[midpoint] === target){
//it does found the value and return
return 'FOUND';
} else if(numbers[midpoint] < target) {
recursiveBinarySearch(numbers.slice(midpoint+1), target);
} else {
recursiveBinarySearch(numbers.slice(midpoint-1), target);
}
}
var result = recursiveBinarySearch([1, 2, 3, 4, 6, 8, 100] , 8);
console.log(result); // Here is returning undefined
谢谢。
答案 0 :(得分:2)
您需要一些return
语句。您也可以省略else
语句,因为如果返回,它就不会执行else
部分。
const recursiveBinarySearch = (numbers, target) => {
const midpoint = Math.floor(numbers.length / 2);
if (numbers[midpoint] === target) {
//it does found the value and return
return 'FOUND';
}
if (numbers[midpoint] < target) {
return recursiveBinarySearch(numbers.slice(midpoint + 1), target);
}
return recursiveBinarySearch(numbers.slice(midpoint - 1), target);
}
var result = recursiveBinarySearch([1, 2, 3, 4, 6, 8, 100] , 8);
console.log(result); // Here is returning undefined