我想按照最短代码行的顺序打印数字 5-0,然后打印数字 0-5。这是我实现的。但是,寻找代码行数较少的任何其他逻辑。期待您的回复。 谢谢,
<html>
<body>
<script>
var n;
function count(n){
console.log(n);
if(n>=1){
return count(n-1);
}
else{
n=1;
count2(n);
}
}
function count2(n){
console.log(n);
if(n<5){
count2(n+1);
}
}
count(5);
</script>
</body>
</html>
最佳答案
您的递归尝试可以这样写:
function count(n, limit=-n){
console.log(Math.abs(n));
if (n>limit) count(n-1, limit);
}
count(5);
在非递归版本中,它将是:
function count(n) {
for (let i = -n; i <= n; i++) console.log(Math.abs(i));
}
count(5);
关于javascript - 如何使用递归打印 1 到 5 和 5 到 1......?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54389767/