你好,我有一个带有" hello"和一个空字符串的数组。问题是我希望能够在数组中打印5倍的Hello字符串,但我遇到了无限的循环。我设置了随机功能和计数器,因为我并不总是想知道我会得到什么参数,但是结果应该是相同的:打印5次"你好"。
这是我的代码:
var a = ["hello", ""];
var randomValue = a[Math.floor(a.length * Math.random())];
function toresult(param){
let counter= 1;
if(param.length >=3 && counter <= 5){
console.log(param)
counter +=1
//If I place the function here I would run into the infinite loop: toresult(randomValue)
} else{
console.log("empty string PRINTED")
}
}
toresult(randomValue)
无限循环发生,因为您没有提供退出子句。现在,您每次调用函数时都重新定义计数器变量。这就是您需要解决的部分。如果未传递给函数https://jsfiddle.net/rfbhk7de/。
var a = ["hello", ""];
var counter = 1;
var randomValue = a[Math.floor(a.length * Math.random())];
function toresult(param){
if(param.length >=3 && counter <= 5){
console.log("Yes, inside!!")
counter +=1
toresult(randomValue)
}else{
console.log("empty string PRINTED")
}
}
toresult(randomValue)
替代选项是,如果没有传递,则还要通过计数器变量并使用计数器的默认值。
var a = ["hello", ""];
var randomValue = a[Math.floor(a.length * Math.random())];
function toresult(param, counter){
counter = typeof(counter) !== "undefined" ? counter : 1; //fancy way of doing an if loop. Basically says if counter is defined then use the passed in counter else set to default 1
if(param.length >=3 && counter <= 5){
console.log("Yes, inside!!")
counter +=1
toresult(randomValue, counter)
}else{
console.log("empty string PRINTED")
}
}
toresult(randomValue)
第二个示例的jsfiddle:https://jsfiddle.net/yd1cxbvc/
我认为递归对此事不利。据我所知
var a = ["hello", ""];
var counter = 0;
do{
randomValue = a[Math.floor(a.length * Math.random())]
if(randomValue.length >=3){
console.info(randomValue);
counter++;
}else{
console.log("empty string PRINTED")
}
}while( counter < 5)
好的。尽管您已经有了答案。这是基于递归的解决方案。
var a = ["hello", ""];
function doPrint(counter){
randomValue = a[Math.floor(a.length * Math.random())]
if(!counter) return;
if(randomValue.length >=3 && counter--){
console.info(randomValue);
}else{
console.log("empty string PRINTED")
}
doPrint(counter);
}
doPrint(5);
递归功能定义有一个或多个基本案例,含义 该函数琐碎产生结果的输入(没有 反复出现)和一个或多个递归情况,意思是输入(s) 该程序恢复(呼叫本身)。
您必须小心地将参数传递到相同的函数呼叫中,如递归,如下所示:
var a = ["hello", ""];
function toresult(count){
if(count < 1) return;
else {
a.push('hello');
return toresult(count-1);
}
}
toresult(5);
console.log(a); // ["hello", "", "hello","hello","hello","hello","hello"]