Skip to main content

Posts

Showing posts with the label Factorialize a Number

recursive in javascript

 递归的思想:取出当前的值,递归当前值以前的所有值。 function   sum ( arr ,  n ) {      let   total = 0 ;    if ( n <= 0 ){      total = 0 ;   } else if (n>arr.length) { return undefined; }       else {      total = arr [ n - 1 ]+ sum ( arr , n - 1 )   }    return   total ;    } console . log ( sum ([ 1 , 3 , 5 ], 3 )); 先考虑极端情况,只有一个元素或者没有元素的情况,那么直接返回0,如果超出了arr的length,则返回无定义 其他情况取当前元素,加上所有以前元素的和。 第二个例子,阶乘, function   factorialize ( num ) {    let   factor  =  0 ;    if  ( num <= 0 ){      factor  =  1 ;   }    else   {      factor  =  num *( factorialize ( num - 1 ));   }    return   factor ; } factorialize ( 5 );