使用递归而不是for循环复制数组项

时间:2016-06-10 23:37:08

标签: javascript arrays recursion

//This function duplicates all array elements(arr) , then add them to newArr 
//and returns newArr  , it works well using for loop , but i want to make a 
//version of this function using recursion instead of for loop

function dubArr(arr){
    newArr=[];
    for(var i=0 ; i<arr.length ; i++){
        newArr.push(2*arr[i]);
    }
    return newArr;
}

// This code uses recursion   

function dubArr(arr){
    newArr=[];

    if(arr.length===0){
        return newArr;
    }
    newArr.push(2*arr[0]);
    arr.shift();
    dubArr(arr);
    return newArr;
}

1 个答案:

答案 0 :(得分:0)

这是函数的递归版本:

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);