为什么即使我返回值,javascript递归函数也返回“未定义”

时间:2019-11-29 13:30:46

标签: javascript binary-search

我正在研究如何在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

谢谢。

1 个答案:

答案 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