Javascript快乐数字不起作用 [英] Javascript Happy Numbers not working
问题描述
这里我有一个函数,应该在disHappy(n)
中输入数字n
来检查是否全部
n in [n-0
)很高兴.
Here I have a function that should take a number n
into the disHappy(n)
to check if all
n in [n-0
) are happy.
如果我只运行happyChecker(n)
,我可以说7很高兴,但是disHappy(n)
没有显示.好像它没有收到真实的.我在所有地方都使用了console.log()'s
,并且happyChecker(n)显示了一个应该返回true的数字.当我在if(newNum===1)
的return true;
上方放置一个console.log()
时,它表明它分支到该分支中,但似乎并没有返回true.
If I only run happyChecker(n)
, I can tell that 7 is happy, but disHappy(n)
doesn't show it. It is as if it doesn't receive the true. I have used console.log()'s
all over the place and happyChecker(n) shows a number that SHOULD return true. When I placed a console.log()
above the return true;
for if(newNum===1)
, it showed that it branched into that branch but it just didn't seem to return the true.
function happyChecker(n) {
var arr = [];
var newNum = 0;
//here I split a number into a string then into an array of strings//
num = n.toString().split("");
for (var i = 0; i < num.length; i++) {
arr[i] = parseInt(num[i], 10);
}
//here I square each number then add it to newNum//
for (var i = 0; i < arr.length; i++) {
newNum += Math.pow(arr[i], 2);
}
//here I noticed that all unhappy numbers eventually came into one of these three//
//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//
if (newNum === 58 || newNum === 4 || newNum == 37) {
return false;
}
if (newNum === 1) {
return true;
} else {
happyChecker(newNum);
}
}
function disHappy(num) {
for (j = num; j > 0; j--) {
if (happyChecker(j)) {
console.log(j + " is a Happy Number. It's so happy!!!.");
}
}
}
推荐答案
递归时,您需要return
返回的值:
When you recurse, you need to return
the value returned:
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
您还应该使用var
声明"num".
You also should declare "num" with var
.
我通常不是代码高尔夫球手",但这是Array原型上的(新)迭代器实用程序方法如何清除代码的一个很好的例子.您可以使用.reduce()
函数遍历数字字符数组,并一次进行平方和求和的工作:
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce()
function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
对.toString()
的调用返回一个字符串,然后.split('')
给您一个数组.然后.reduce()
以初始和0开头,并且对于数组的每个元素(每个数字),将其添加到该数字的平方. (我不是使用+
而是使用+
一元运算符;我们确定每个字符串都是有效数字和整数.)
The call to .toString()
returns a string, then .split('')
gives you an array. Then .reduce()
starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt()
I just used the +
unary operator; we know for sure that each string will be a valid number and an integer.)
这篇关于Javascript快乐数字不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!