为什么即使我返回值,javascript递归函数也返回“未定义" [英] Why is javascript recursive function returning 'undefined' even when I am returning a value

查看:59
本文介绍了为什么即使我返回值,javascript递归函数也返回“未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何在javascript函数中实现二进制搜索,发现当我返回该值并将其保存到变量中时,然后在我进行console.log时,这是未定义的.

I am looking at how to implement binary search in a javascript function and found that when I return the value and save it into a variable then when I console.log this comes as undefined.

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

提前谢谢.

推荐答案

您需要一些 return 语句.您也可以省略 else 语句,因为如果返回该语句,它将不执行 else 部分.

You need some return statements. You could omit the else statements as well, because if returned, it does not execure the else part.

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

这篇关于为什么即使我返回值,javascript递归函数也返回“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆