Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
Qn-print and write all array element using recursion in JavaScript cuz i'm new to the concept of recursion i couldn't able to figure out the problem

Here is my code and I know there is some mistake in my code but I'm new to the concept of recursion. I think there is a problem cuz I tried to implement the same code as the C language. I want my answer to read and print array by using recursion And I tried to convert the c code into javascript, c++ code into javascript and lastly in python code into javascript.

var a = [1, 2, 3];
var l = a.length;
var num = 0;

function printArr(a, i, l){
  for(var i=0; i<l; i++){
    num = a[i];
  }
  if(i>=l){
    return 0;
    printArr(a, i+1, l);  //<I think in this section I'm having a problem.>
  }
}

printArr(a, 0, l); 
console.log(num);   
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No need for that for loop.

Your printArr call should be outside if statement.

var a = [1, 2, 3];
var l = a.length;
//var num = 0; // not needed

function printArr(a, i, l) {
  // Base condition - to break out of recursion
  // check if index is out of array bounds, if yes return
  if (i >= l) {
    return;
  }

  // if not, print the array element at that index
  console.log(a[i]);

  // call the recursive function with next consecutive index
  printArr(a, i + 1, l);
}

printArr(a, 0, l);  

about 4 years ago · Juan Pablo Isaza Relatório

0

Another method would allow us to avoid mucking about with indices at all, destructuring the input array and checking whether the first element is empty:

const printArr = ([x, ...xs]) => {
  if (x == null) return null
  console .log (x)
  return printArr (xs)
}

printArr ([1, 2, 3])

I would personally prefer to write this as a single expression, like this:

const printArr = ([x, ...xs]) => 
  x == null ? null : (console .log (x), printArr (xs))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda