How to save the variable, without changing the scope

1

Is it impossible to save the value of the variables without placing them outside? For the purpose of doing the function in an iterative way, do it recursively.

If there really is no way, why?

Save the value of the variables that are inside the function in order to do the function recursively, instead of using loops.

The purpose of the function is to show the table of a number, in this way the first parameter is the number of which you want to know the table , and the second the table size , so if the parameters are (4,10) would be the table from 4 to 10 bone, (4*1 ... 4*10)

function ab(n,max){ 
 var maximo=parseInt(max,10) || 0, // el maximo
     contador = 1, // un contador
     numeroParaMultiplicar = parseInt(n,10) || 0, // el numero para la tabla
     numerosMultiplicados = []; // aqui se añadirá la tabla
if(contador <= maximo) { // mientras el contador sea igual o menor que el maximo especifcado se realizara el bucle
    //numerosMultiplicados.push(numeroParaMultiplicar*contador);
    numerosMultiplicados.push(numeroParaMultiplicar*contador); //multiplico
    contador++; // se suma 1 al contador
    ab(numeroParaMultiplicar,maximo); //vuelvo a llamar a la funcion
 }
 return numerosMultiplicados;
}

console.log(ab(4,10));
    
asked by Eduardo Sebastian 11.10.2017 в 04:23
source

1 answer

1

It is not necessary to have a loop to perform all the multiplications, you can simply invoke the function with the number to multiply next / previous until you reach a base case.

The results can be accumulated in an array, passing it as a parameter of the function, initializing it in its invocation as an empty array. Or simply print them.

This recursive function has:

  • Base case: n*0 = 0
  • Recursive case: invokes the function with max-1 , that is% n*max , n*(max-1) , n*(max-2) ... n*(max-max) = n*0 . For example starting from 4 * 10 and continuing recursive calls with 4 * 9, 4 * 8 .... 4 * 1, 4 * 0

function multTable(n,max,results){
   if(max === 0){
     results.push(0);
     return results;
   }else{
      results.push(n*max);
      return multTable(n,max-1,results);
   }
}

console.log(multTable(4,10,[]));
console.log(multTable(3,10,[]));
console.log(multTable(10,10,[]));
console.log(multTable(4,5,[]));
console.log(multTable(4,0,[]));

Also, be careful how you have defined the recursion in your current implementation, since it results in an infinite loop. each new invocation to ab assigns the value 1 to contador , and maximo is always 10, so the cut condition contador>máximo will never evaluate true

    
answered by 11.10.2017 / 04:56
source