54 lines
1.8 KiB
HTML
54 lines
1.8 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 44: Quersumme berechnen</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">
|
|
<h1>Übung 44: Quersumme berechnen</h1>
|
|
<p>
|
|
Schreibe eine Funktion digitSum, die die Quersumme einer übergebenen Zahl zurückgibt.
|
|
<strong>Hinweis:</strong> Die Quersumme ist die Summe aller Ziffern einer Zahl. <br /><strong>Tipp:</strong>
|
|
Verwenden Sie split('').
|
|
</p>
|
|
<div class="output alert alert-secondary my-3"></div>
|
|
</div>
|
|
</div>
|
|
</main>
|
|
<script>
|
|
'use strict';
|
|
|
|
const outputEl = document.querySelector('.output');
|
|
|
|
const number = 4566;
|
|
|
|
const getDigitSum = (n) => {
|
|
// n in ein array umwandeln
|
|
const digitAr = String(n).split(''); // (n).toString().split('')
|
|
// => z.B. ['4','2','4','2']
|
|
// Die quersumme berechnen und zurückgeben
|
|
return digitAr.reduce((digit1, digit2) => Number(digit1) + Number(digit2), 0);
|
|
};
|
|
|
|
const getDigitSum1 = (n) => {
|
|
return String(n) // => '4242'
|
|
.split('') // => ['4','2','4','2']
|
|
.map((str) => Number(str)) // => .map(Number) [4,2,4,2]
|
|
.reduce((sum, n) => sum + n, 0); //=> 12
|
|
};
|
|
|
|
console.log(getDigitSum(4242)); //=> 12
|
|
console.log(getDigitSum('13')); //=> 4
|
|
console.log(getDigitSum(134)); //=> 8
|
|
|
|
outputEl.textContent = `Die Quersumme von ${number} ist: ${getDigitSum(number)}!`;
|
|
//========
|
|
</script>
|
|
</body>
|
|
</html>
|