【发布时间】: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