[Answer] How should this JavaScript recursive function be understood?
![[Answer] How should this JavaScript recursive function be understood?](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2Fjavascript-0b046349.png&w=3840&q=75)
[Answer] How should this JavaScript recursive function be understood?
[Answer] How should this JavaScript recursive function be understood?
Recursion means solving a repetitive problem by repeatedly calling the function itself. In this example, recursion is used to calculate the Fibonacci sequence, which is also a classic problem often solved with recursion.
This sample supports direct invocation with an input argument. If no Fibonacci parameter is provided when calling it, you need to enter a number from the command line and then perform the calculation.
// JavaScript command-line input/output
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Fibonacci sequence function, recursive call
function fibo(index) {
if (parseInt(index) === 1 || parseInt(index) === 2) {
return 1;
} else {
return fibo(parseInt(index) - 1) + fibo(parseInt(index) - 2);
}
}
// If a number is passed when invoking the script, compute it directly
if (process.argv.length > 2) {
let index = parseInt(process.argv[2]); // argv[0] is node.exe, argv[1] is the filename
console.log(`the fibonacci sequence of ${index} is ${fibo(index)}`);
process.exit(0);
}
// If no number is provided when invoking, enter it here
console.log("please input an integer to calculate the fibonacci sequence");
rl.on('line', (index) => {
console.log(`the fibonacci sequence of ${index} is ${fibo(index)}`);
rl.close();
});
![[Thought] Many viruses you’ve probably never heard of also contain DNA, such as iridoviruses](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2Fdna-39161584.png&w=3840&q=75)
![[Answer] What did you do on the night you checked your Gaokao score?](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2F-e4a8ec38.png&w=3840&q=75)
![[Answer] How Can You Score 130+ on the Gaokao Math Exam?](/_next/image?url=https%3A%2F%2Flxunzzzdnokdqhipbmdf.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fmedia%2Fcovers%2F130-157dba52.png&w=3840&q=75)