function reccursion(){
let random=Math.floor(Math.random()*9);
if(squares[random]==null){
// Here I'm getting the random between 0-8 range in console but in switch statement sometimes returning undefined
console.log(random,'random value generated')
switch(random){
case 0:
return 0
case 1:
return 1
case 2:
return 2
case 3:
return 3
case 4:
return 4
case 5:
return 5
case 6:
return 6
case 7:
return 7
case 8:
return 8
}
}else{
reccursion();
}
}
在这里,我创建了递归函数,其中如果随机选择的平方“(长度为 9 且索引为 0-8 的数组)”的任何值为 null,那么我应该返回其索引 no,这是随机值。但有时即使正方形中存在空值,它也会给我未定义
您忘记了 else 分支中的 return 语句:
尝试这段代码,它永远不会返回未定义。
function reccursion(){
let random=Math.floor(Math.random()*9);
if(squares[random]==null){
// Here I'm getting the random between 0-8 range in console but in switch statement sometimes returning undefined
console.log(random,'random value generated')
switch(random){
case 0:
return 0
case 1:
return 1
case 2:
return 2
case 3:
return 3
case 4:
return 4
case 5:
return 5
case 6:
return 6
case 7:
return 7
case 8:
return 8
}
}else{
return reccursion();
}
}