recursion - Recursive function in Javascript to fill Array? -


i trying fill array ranges of values in recursive function, see weird thing happening while returning array, though array has values, when alert outside function gives me undefined. not sure whether code issue or kind of behavior.

same implementation when tired using simple loop worked fine.

i don't know title give problem, please suggest me one.

js fiddle

with recursion

var arr = []; function fillarray(n,i){     if(arr.length !== n){         if(i===0)             arr[i] = i;         else             arr[i] = arr[i-1] + 1;         fillarray(n,++i);     }     else{          console.log(arr);          return arr;     } } console.log(fillarray(10,0)); 

with loop

var arr = [];  function fillarray(start,end){     for(var i=start,j=0;i<=end;i++,j++){         arr[j] = i;     }     return arr; }  alert(fillarray(1,10)); 

function fillarray(n, i, a) {    a.push(i);    return a.length < n ? fillarray(n, ++i, a) : a;  }    console.log(fillarray(10, 0, []));


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -