javascript - Duplicate array items using recursion instead of for loop -


//this function duplicates array elements(arr) , add them newarr  //and returns newarr  , works using loop , want make  //version of function using recursion instead of loop  function dubarr(arr){     newarr=[];     for(var i=0 ; i<arr.length ; i++){         newarr.push(2*arr[i]);     }     return newarr; }  // code uses recursion     function dubarr(arr){     newarr=[];      if(arr.length===0){         return newarr;     }     newarr.push(2*arr[0]);     arr.shift();     dubarr(arr);     return newarr; } 

here recursive version of function :

function dubarr(arr, index, newarr){   if (!newarr)     newarr = new array();   if (index < arr.length) {    newarr.push(2*arr[index]);    index++;    return dubarr(arr, index, newarr);   }   return newarr; }  var tab = [12, 2, 36, 14]; var newtab = dubarr(tab, 0); console.log(newtab); 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -