af2111: Variablennamen durch Variable bestimmen

Beitrag lesen

Danke für den tipp mit dem array, jetzt passt alles. Der HTML Code ist:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Objekte</title>
    <script src="Objects.js"></script>
</head>
<body>
    <fieldset>
    <label for="firstname">
            Vorname  <input id="firstname" type="text" placeholder="Dein Name">  <br><br>
    </label>
    <label for="lastname">
            Nachname  <input id="lastname" type="text" placeholder="Dein Nachname"><br>  <br> 
</label>
<label for="age">
        Alter <input id="age" type="text" placeholder="Dein Alter"><br> <br>
</label>
    <input id="sub" type="button" value="Abschicken"><br><br>
    </fieldset>
    <div id="Persons">

    </div>
</body>
</html>

Der JavaScript Code ist:

document.addEventListener("DOMContentLoaded", function() {

let start = document.getElementById("sub");
start.addEventListener("click", function() {

    let Vorname = document.getElementById("firstname").value;

    let Nachname = document.getElementById("lastname").value;

let Alter = document.getElementById("age").value;



let Persons = document.getElementById("Persons")
let Datenspeicher = [];
let Daten = {
    Vorname: Vorname,
    Nachname: Nachname,
    Alter: Alter,
    PrintPerson: function(p) { Persons.innerText = p.Vorname + " " + p.Nachname + " ist " + p.Alter + " Jahre alt." 
    
    }
    }
Datenspeicher.push(Daten)
Daten.PrintPerson(Datenspeicher[Datenspeicher.length - 1]);
console.log(Datenspeicher);


let Farben = [
    "yellow",
    "orange",
    "red",
    "lightblue",
    "blue",
    "fuchsia",
    "pink",
    "gold",
    "lightgreen",
    "green",
    ""
]

document.body.style.backgroundColor = Farben[Math.floor(Math.random() * 10)];


});


});

Probier das mal aus. 😀😀😀😀