Files
2026-09-24 10:25:47 +02:00

51 lines
1.7 KiB
HTML

<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 10: Summe aller Zahlen in einem verschachtelten Array</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>
Übung 10: Summe aller Zahlen in einem verschachtelten Array
<span class="badge text-bg-warning">Optional</span>
</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 sollte nur Zahlen oder weitere Arrays
enthalten.
</p>
</div>
</div>
</main>
<script>
'use strict';
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
console.log(sumNestedArray([[[[1]]], 2, [3, [4, [5]]]])); // => 15
console.log(sumNestedArray([])); // => 0
console.log(sumNestedArray([10, [20, [30, [40]]]])); // => 100
console.log(sumNestedArray([1, 'a', [2, 'b', [3, 4]], 5])); // => 15 (ignoriert Nicht-Zahlen)
</script>
</body>
</html>