[英]Why does this recursive javascript function return what it does?
var fn = function even (n) {
if (n === 0) {
return true
}
else return !even(n - 1)
}
fn(5)//=> false
fn(2) //=> true
Why does this function work the way it does? 为什么此功能按其方式工作? When I step through it when the argument is 5 it seems to call itself until n is zero which would return true but it returns false.
当我在参数为5时逐步执行它时,它似乎会自行调用,直到n为零为止,这将返回true,但返回false。
Every recursion step adds a negation to the previous result: 每个递归步骤都会对先前的结果添加一个否定值:
f(0) = true
f(1) = !f(0) = !true = false
f(2) = !f(1) = !!f(0) = !!true = !false = true
and so on, for f(5) you get 依此类推,对于f(5),您得到
f(5)
!f(4)
!!f(3)
!!!f(2)
!!!!f(1)
!!!!!f(0)
!!!!(!true)
!!!(!false)
!!(!true)
!(!false)
!true
false
it's because of the ! 这是因为!
When the function is 0 it return true. 当该函数为0时,它返回true。
When it's 1 it will return !even(0) -> false. 如果为1,它将返回!even(0)-> false。
When it's 2 it will return !even(1) => !(!even(0)) => !(false)=> true. 如果为2,它将返回!even(1)=>!(!even(0))=>!(false)=> true。
Since boolean is either true of false, meaning two possible value and you switch them again and again it works. 由于布尔值为true或false,表示两个可能的值,而您一次又一次地切换它们就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.