简单函数返回“未定义"值 [英] Simple function returning 'undefined' value
问题描述
这是我目前正在使用的功能:
This is the function I am currently working on:
function getSmallestDivisor(xVal) {
if (xVal % 2 === 0) {
return 2;
} else if (xVal % 3 === 0) {
return 3;
} else {
var xSqrt = Math.sqrt(xVal);
if (xSqrt % 1 === 0) {
getSmallestDivisor(xSqrt);
} else {
return xVal;
}
}
}
alert(getSmallestDivisor(121));
我已经设计了上面的函数来返回整数的最低除数.考虑情况 121
.它实际上应该在当前上下文中返回 11
.但它返回的是 undefined
.
I had designed the above function to return the lowest divisor of an integer. Consider the case 121
. It should actually return 11
in the current context. But it is returning undefined
.
我检查了递归调用发生了多少次;他们实际上发生了两次.我在这两个不同的调用中记录了 xVal
的值,它们显示了 121
和 11
.我在这里真的很困惑为什么此函数当前返回 undefined
.
I have checked how many times the recursive calls happened; they actually happened two times. I logged the values of xVal
in those two different calls, and they display 121
and 11
. I am really confused here about why this function is currently returning undefined
.
我创建了一个jsfiddle演示.
推荐答案
if (xSqrt % 1 === 0) {
return getSmallestDivisor(xSqrt); // missing return here
} else {
return xVal;
}
演示:小提琴
这篇关于简单函数返回“未定义"值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!