This commit is contained in:
55
06_js-debug/uebungen/u09_parse-user-data/solution.html
Normal file
55
06_js-debug/uebungen/u09_parse-user-data/solution.html
Normal file
@@ -0,0 +1,55 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 9: parseUserData Fehler</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">
|
||||
<h1>Übung 9: parseUserData Fehler</h1>
|
||||
<p>Die Kommentare zeigen das erwartete Ergebnis.</p>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
function parseUserData(jsonString) {
|
||||
try {
|
||||
const userData = JSON.parse(jsonString);
|
||||
|
||||
// hinzugefügt
|
||||
if (typeof userData.name === 'undefined') {
|
||||
return 'Error: name ist nicht vorhanden!';
|
||||
}
|
||||
|
||||
if (typeof userData.age === 'undefined') {
|
||||
return 'Error: age ist nicht angegeben';
|
||||
}
|
||||
if (typeof userData.name !== 'string') {
|
||||
return 'Error: name ist nicht vom Typ string!';
|
||||
}
|
||||
|
||||
if (typeof userData.age !== 'number') {
|
||||
return 'Error: age ist nicht vom Typ number';
|
||||
}
|
||||
// end
|
||||
|
||||
return `User: ${userData.name}, Age: ${userData.age}`;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
return `Error: ${error.message}`;
|
||||
}
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(parseUserData('{"name": "Alice", "age": 30}')); // => 'User: Alice, Age: 30'
|
||||
console.log(parseUserData('{"name": "Bob", "age": "thirty"}')); // => 'Error: Invalid data types'
|
||||
console.log(parseUserData('{"age": "thirty"}')); // => 'Error: Invalid data types'
|
||||
console.log(parseUserData('{"name": "Bob"}')); // => 'Error: Invalid data types'
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user