Rekursion bitte in javascript?

2 Antworten

Hi BarakaMimon,

das geht folgendermaßen in JavaScript:

function countUp(Ende, current = 0) { 
if (current > Ende) return;
console.log(current);
countUp(Ende, current + 1);
}
function main() { countUp(10); }
main();

Andere Variante:

function countUp(Ende) {
    if (Ende < 0) return;
    countUp(Ende - 1);
    console.log(Ende);
  }
  
  function main() {
    countUp(10);
  }
  
  main();

OOP-Variante:

class Counter {
    static countUp(end, current = 0) {
      if (current > end) return;
      console.log(current);
      Counter.countUp(end, current + 1);
    }
  }
  
  function main() {
    Counter.countUp(10);
  }
  
  main();

Es gibt noch weitere Möglichkeiten so etwas in JavaScript zu implementieren.

Woher ich das weiß:Berufserfahrung – Ich bin gelernter Mediengestalter Digital und Print(IHK)

function countUp(Ende) {

if (Ende>0) {

countUp(Ende-1);

}

console.log(Ende);

}

countUp(10);


BarakaMimon 
Beitragsersteller
 28.11.2024, 00:24

vielen Dank, smarter boi, nichtmal chatgpt hat es hingekriegt