This commit is contained in:
Philippe Torrel
2026-09-24 10:25:47 +02:00
parent db1626eb30
commit 6887814561
7 changed files with 174 additions and 3 deletions
@@ -16,7 +16,8 @@
</h2>
<p>
Schreibe eine rekursive Funktion in JavaScript, die die Summe aller Zahlen in einem verschachtelten Array
berechnet. Das Array kann beliebig tief verschachtelt sein und enthält nur Zahlen oder weitere Arrays.
berechnet. Das Array kann beliebig tief verschachtelt sein und sollte nur Zahlen oder weitere Arrays
enthalten.
</p>
</div>
</div>
@@ -24,7 +25,19 @@
<script>
'use strict';
const sumNestedArray = (arr) => {};
const sumNestedArray = (arr) => {
let sum = 0;
arr.forEach((value) => {
if (Array.isArray(value)) {
sum += sumNestedArray(value); // 1 + 2 + 3 +
} else if (typeof value === 'number') {
sum += value; // 4 + 5 + 6
}
});
return sum;
};
// Test cases
console.log(sumNestedArray([1, [2, [3, 4], 5], 6])); // => 21
@@ -0,0 +1,55 @@
// Variante 1
const printWords = (text = '', idx = 0) => {
const words = text.split(' '); //=> ['KI-Entwickler', 'warnen', 'UN-Gremium']
// Basisfall
if (idx >= words.length) return; // Abbruch
console.log(words[idx]); // KI-Entwickler
setTimeout(() => {
printWords(text, ++idx);
}, 1000);
};
// printWords('KI-Entwickler warnen UN-Gremium');
const printWordsFor = (sentence) => {
const wordArr = sentence.split(' ');
for (let i = 0; i < wordArr.length; i++) {
setTimeout(() => {
console.log(wordArr[i]);
}, 1000 * i);
}
};
printWordsFor('Bundestag berät über Organspende');
// setTimeout(() => {
// console.log('The');
// setTimeout(() => {
// console.log('pyramid');
// setTimeout(() => {
// console.log('of');
// setTimeout(() => {
// console.log('doom');
// setTimeout(() => {
// console.log('keeps');
// setTimeout(() => {
// console.log('growing.');
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// Übung 11: Die Pyramide abbrechen
// Schreibe das Codebeispiel 96 so um, dass keine Pyramide entsteht. Benutze dazu, wie im Text angedeutet, eine Funktion, die das n-te Wort ausgibt und sich per setTimeout(…) mit n + 1 als Parameter aufruft, solange noch Wörter im Satz vorhanden sind.