I need to make a Fibonacci sequence and I found this code below here. When I try to understand all code, I saw "(i <= 1) ? i : arr[i-2] + arr[i-1]" I thought that was an simple if else shortcut condition, and I try to replace by the extended way just to be sure (see the last code). But now the code didn't work...
//Stackoverflow code:
function fib(n){
return new Array(n).fill(1).reduce((arr, _ ,i) => {
arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
return arr
},[]) ;
}
console.log(fib(10))
//My code with (extended if else):
function fib(n){
return new Array(n).fill(1).reduce((arr, _ ,i) => {
arr.push(if (i <= 1) {
i
} else {
arr[i-2] + arr[i-1]
})
return arr
},[]) ;
}
console.log(fib(10))
Why my code do not work? Is "(i <= 1) ? i : arr[i-2] + arr[i-1]" a kind of if/else statement?
Aucun commentaire:
Enregistrer un commentaire