我一直在 codepen.io 上创建一个程序作为学校的业余项目,它的作用是找出一个快乐数字列表。它以一个数字数组开始(在本例中我使用了 1,2,3),对于数组中的每个数字,执行 while 循环,迭代检查确认的“不愉快的数字”,并执行计算生成新数字等 这是我使用的代码:
var list = [1, 2, 3]
// var list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
var badlist = []
var goodlist = [1]
var baddiglist = []
var gooddiglist = []
for (let i = 0; i < list.length; i++) {
var ex = list[i]
var cycle = true
var diglist = []
var numblist = []
while(cycle) {
var digits = []
var resnumb = 0
if (badlist.includes(ex)) {
badlist.push(...numblist)
cycle = false
} else if (numblist.includes(ex)) {
badlist.push(...numblist)
cycle = false
} else if (goodlist.includes(ex)) {
goodlist.push(...numblist)
} else {
digits = ex.split().map(Number)
digits.sort((a, b) => a - b)
if (baddiglist.includes(digits)) {
badlist.push(...numblist)
baddiglist.push(...diglist)
cycle = false
} else if (diglist.includes(digits)) {
badlist.push(...numblist)
baddiglist.push(...diglist)
cycle = false
} else if (gooddiglist.includes(digits)) {
goodlist.push(...numblist)
gooddiglist.push(...diglist)
cycle = false
} else {
numblist.push(ex)
diglist.push(digits)
for (let n = 0; n < digits.length; n++) {
resnumb += n ** 2
}
ex = resnumb
}
}
}
goodlist.sort((a, b) => a - b)
badlist.sort((a, b) => a - b)
}
console.log(goodlist)
console.log(badlist)
注意:第二个数组(list2)尚未在程序中使用
我检查了代码,看看是否忘记初始化任何变量,是否将任何代码行放在错误的位置,或犯了任何其他错误,在这个过程中我发现并修复了一堆可能会导致以后出现问题的问题如果我能够运行该程序的话。
但是无论我怎么尝试,控制台都只显示这个:
"[CodePen]: An infinite loop (or a loop taking too long) was detected, so we stopped its execution. More details at https://blog.codepen.io/2016/06/08/can-adjust-infinite-loop-protection-timing/"
哦,还有这个
// [object Array] (1)
[1]
// [object Array] (0)
[]
并且此错误消息不断显示在 Javascript 窗口中:
Infinite loop found around line 0. The line number is approximated so look carefully. More details and workarounds at https://blog.codepen.io/2016/06/08/can-adjust-infinite-loop-protection-timing/
(0号线存在吗??)
我的代码是否存在逻辑错误,或者代码是否太长而无法在 Codepen.io 中执行?如果是后者,有什么方法可以简化代码,让 Codepen.io 可以处理吗?
您可以使用
Set
来表示看到的数字,并在看到的值再次出现时停止迭代/递归。
为了获取数组,需要池化到末尾以将值添加到 good 或 bad 数组。
good
使用所需的目标编号进行初始化。
const
good = [1],
bad = [],
newNumber = v => v.toString().split('').reduce((t, d) => t + d * d, 0),
isHappy = (v, seen = new Set) => {
if (good.includes(v)) return true;
if (bad.includes(v)) return false;
if (seen.has(v)) return false;
seen.add(v);
const result = isHappy(newNumber(v), seen);
if (result) good.unshift(v);
else bad.unshift(v);
return result;
};
console.log(isHappy(19));
console.log(...good);
console.log(...bad);