【问题标题】:Why does this function return undefined, even though the variable exists? [duplicate]为什么这个函数返回未定义,即使变量存在? [复制]
【发布时间】:2020-06-20 17:46:28
【问题描述】:

此时我已经尝试console.log() 几乎所有内容。我失踪可能有一个简单的原因,但我真的无法考虑。代码如下:

const primes = [];

//Function to determine if a number is prime
function isPrime(num) {
    for (let i = 2; i < num; i++)
        if (num % i === 0 && num > 1) return false;
    return true;
}

//Cycling through the number up until 100 and adding the primes to the array
for (let i = 0; i < 100; i++) {
    if (isPrime(i)) primes.push(i);
}

let min = 0, max = primes.length;

//Binary search algorithm
function binarySearch(array, target) {
    let guess = Math.floor((min + max) / 2);

    if (array[guess] === target) return guess;

    if (array[guess] < target) min = guess + 1;
    else max = guess - 1;

    binarySearch(array,target);
}

console.log(binarySearch(primes, 3));

我不明白为什么我得到 undefined 作为输出,即使有一个应该返回变量guess 的返回函数。

【问题讨论】:

    标签: javascript function return undefined


    【解决方案1】:

    很可能你得到了undefined,因为你忘了从binarySearch函数返回。

    尝试如下:

    function binarySearch(array, target) {
        // ... implementation
    
        return binarySearch(array,target);
    }
    

    我希望这会有所帮助!

    【讨论】:

    • 谢谢!非常头疼,就这么简单;无论如何,谢谢你让我不再头疼!
    猜你喜欢
    • 2011-05-07
    • 2021-01-14
    • 2017-07-23
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2016-09-24
    • 2016-08-12
    相关资源
    最近更新 更多