【问题标题】:creating objects and arrays of object创建对象和对象数组
【发布时间】:2020-03-14 12:25:52
【问题描述】:

我的 JavaScript 作业有点卡住了。以下是要求

  1. 创建一个新的 JavaScript 文件。在这个文件中创建一个创建动物对象的构造函数。动物对象应存储以下属性:

    • Name – 动物的名字
    • 性别 - 动物的性别
    • 物种——动物的物种
  2. 创建一个全局数组,用于存储未知数量的动物对象。

  3. 创建一个 addAnimal() 函数,该函数在单击“添加动物”按钮时运行。这个函数应该做以下事情:

    • 从用户输入字段中确定动物的名称、性别和物种
    • 根据用户信息创建动物对象
    • 将动物对象推到阵列上
    • 更新输出/显示
  4. 创建一个函数,将数组中存储的所有动物显示为页面上的无序列表。

到目前为止,这是我在 html 文档中所写的内容。我一直在为此苦苦挣扎,我不确定如何正确实现构造函数:

<!DOCTYPE HTML 5.13.14>
<html>
    <head>
    <link type="text/css" rel="stylesheet" 
      href="ex12.js">
    <title> Alleluia CPSC 1045 Exersize 12         </title>

     <script>

     function addAnimal(name, type, gender) {
        this.name = name,
        this.type = type,
        this.gender = gender,
        this.result = function addAnimal() {

            onclick return this.name +   this.type + this.gender;
        }
    }

       </script>
      </head>

      <body>
      <h1> Welcome to the CPSC 1045 Zoo!</h1>
      <br>
      <p> Please add an animal to the zoo by  filling out the following feilds</p>
      <br>
      <p> Animal Name: <input type="text"     id="name" name="inputname"></p>
      <p> Animal Type: <input type="text"    id="type" name="inputtype"></p>

     <!--- radio input --->
     <p> Animal Gender: 
        <input type="radio" name="gender"      value="Male" id="genderm"> Male
         <input type="radio" name="gender"   value="Female" id="genderf"> Female
       </p> 
      <!--- end--->

      <button type="button"     onclick='addAnimal()' id="result"><b>Add      Animal</b></button>

</body>
</html>

【问题讨论】:

  • 为什么要标记这是一个 Java 问题?这似乎与 Java 编程没有任何关系。请仔细检查问题标签(在底部),因为您不想吸引错误的专家来回答您的问题。
  • 我的坏兄弟。在那里,固定。

标签: javascript html arrays string


【解决方案1】:

创建一个新的 JavaScript 文件。在这个文件中创建一个创建动物对象的构造函数。动物对象应存储以下属性:

  • 名字——动物的名字
  • 性别 - 动物的性别
  • 物种——动物的物种
 animals.push({
  id: animals.length + 1,
  name: animal_name.value,
  gender: animal_gender.value,
  species: animal_species.value
});

创建一个将存储未知数量的动物对象的全局数组。

let animals = [];

创建一个 addAnimal() 函数,该函数在单击“添加动物”按钮时运行。这个函数应该做以下事情:

  • 从用户输入字段中确定动物的名称、性别和种类
  • 根据用户信息创建动物对象
  • 将动物对象推到阵列上
  • 更新输出/显示
function addAnimal() {
  var animal_name = document.getElementById('name');
  var animal_gender = document.getElementById('gender');
  var animal_species = document.getElementById('species');

    animals.push({
      id: animals.length + 1,
      name: animal_name.value,
      gender: animal_gender.value,
      species: animal_species.value
    });
  }

创建一个函数,将存储在数组中的所有动物显示为页面上的无序列表。

function updateDisplay(identifier) { 
    var animal = animals.find(obj => {
      return obj.id === identifier
    }); 
  var table = document.getElementById('animals').getElementsByTagName('tbody')[0];
    var newRow = table.insertRow();
  //Col 1
  var newCell = newRow.insertCell(0);
  var newText = document.createTextNode(animal.name);
  newCell.appendChild(newText);
  //Col 2
  newCell = newRow.insertCell(1);
  var newText = document.createTextNode(animal.gender);
  newCell.appendChild(newText);
  //Col 3
  newCell = newRow.insertCell(2);
  var newText = document.createTextNode(animal.species);
  newCell.appendChild(newText);
}

错误处理未在要求中涵盖,但对于验证要添加到数组中的数据是否确实存在很有用。根据:

function handleErrors(name, gender, species) {
  var error = document.getElementById('error');
  var errorText = "";

  if (name == null || name.value == '') {
    errorText += "Name cannot be blank. ";
  }

  if (gender == null || gender.value == '') {
    errorText += "Gender cannot be blank. ";
  }

  if (species == null || species.value == '') {
    errorText += "Species cannot be blank. ";
  }

  if (errorText != "") {
    error.classList.remove("hidden");
    error.innerText = errorText;
    return true;
  } else {
    return false;
  }
}

请注意,此示例与其他示例之间的差异有所不同,但此示例提供:

  • 数据验证后向数组添加项
  • 使用内置 Javascript函数insertCellinsertRowcreateTextNode向表中添加行

查看完整示例:

let animals = [];

function updateDisplay(identifier) { 
	var animal = animals.find(obj => {
      return obj.id === identifier
    }); 
  var table = document.getElementById('animals').getElementsByTagName('tbody')[0];
	var newRow = table.insertRow();
  //Col 1
  var newCell = newRow.insertCell(0);
  var newText = document.createTextNode(animal.name);
  newCell.appendChild(newText);
  //Col 2
  newCell = newRow.insertCell(1);
  var newText = document.createTextNode(animal.gender);
  newCell.appendChild(newText);
  //Col 3
  newCell = newRow.insertCell(2);
  var newText = document.createTextNode(animal.species);
  newCell.appendChild(newText);
}

function addAnimal() {
  var animal_name = document.getElementById('name');
  var animal_gender = document.getElementById('gender');
  var animal_species = document.getElementById('species');

  if (!handleErrors(animal_name, animal_gender, animal_species)) {
    animals.push({
      id: animals.length + 1,
      name: animal_name.value,
      gender: animal_gender.value,
      species: animal_species.value
    });
    updateDisplay(animals.length);
  }
}

function handleErrors(name, gender, species) {
  var error = document.getElementById('error');
  var errorText = "";

  if (name == null || name.value == '') {
    errorText += "Name cannot be blank. ";
  }

  if (gender == null || gender.value == '') {
    errorText += "Gender cannot be blank. ";
  }

  if (species == null || species.value == '') {
    errorText += "Species cannot be blank. ";
  }

  if (errorText != "") {
    error.classList.remove("hidden");
    error.innerText = errorText;
    return true;
  } else {
    error.classList.add("hidden");
    error.innerText = "";
    return false;
  }
}
.wrapper {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  margin-left: auto;
  margin-right: auto;
  background-color: lightgray;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  padding: 35px;
}

.wrapper * {
  margin: 5px;
  padding: 5px;
}

.wrapper button {
  height: 40px;
  opacity: 0.8;
}

.wrapper button:hover {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  opacity: 1;
}

.hidden {
  display: none;
}

.error {
  color: darkred;
  text-align: center;
}

table {
  max-width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding: 35px;  
}

table th {
  width: 23vw;
  background-color: lightgray;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

table tr {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  }
  
table tr:nth-child(even) {
  background-color: #f2f2f2;
  }
<div class="wrapper">
  <input type="text" id="name" placeholder="Animal Name" />
  <input type="text" id="gender" placeholder="Animal Gender" />
  <input type="text" id="species" placeholder="Animal Species" />
  <button type="button" onclick="addAnimal()">Add Animal</button>
  <label id="error" class="hidden error"></label>
</div>

<table id="animals">
  <thead>
    <tr>
      <th> Name </th>
      <th> Gender </th>
      <th> Species </th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

请参阅这些以供参考:

【讨论】:

    【解决方案2】:
    <!DOCTYPE html>
    <html lang="en">
    
    <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>Document</title>
    </head>
    
    <body>
    
        <!-- from the user input fields -->
        <fieldset>
            <legend>Animal</legend>
            <div>
                <label for="name">Name: </label>
                <input type="text" id="name">
            </div>
            <div>
                <label>Gender</label>
                <input type="radio" id="male" name="gender" value="Male">
                <label for="kraken">Male</label>
                <input type="radio" id="female" name="gender" value="Female">
                <label for="female">Female</label><br />
    
            </div>
            <div>
                <label for="species">Species: </label>
                <input type="text" id="species">
            </div>
    
            <button onclick="addAnimal()"> Add Animal</button>
        </fieldset>
    
    
        <hr>
        <hr>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Gender</th>
                    <th>Species</th>
                </tr>
            </thead>
    
            <tbody id="animal-list">
    
            </tbody>
        </table>
    
        <script>
            //Create a global array that will store an unknown number of animal objects.
            var animalStore = [];
            // Create a new JavaScript file. Inside this file create a constructor that creates animal objects. An animal object should store the following properties:
            // Name – the name of the animal
            // Gender – the gender of the animal
            // Species – the species of the animal
            function Animal(name, gender, species) {
                this.name = name;
                this.gender = gender;
                this.species = species;
            }
    
            // Create an animal object from the user information
            //Create an addAnimal() functions that runs when the Add Animal button is clicked. This function should do the following things:
            function addAnimal() {
                let name = document.getElementById('name').value;
                let gender = Array.from(document.getElementsByName('gender')).filter(o => o.checked)[0].value;
                let species = document.getElementById('species').value;
                let animalInstance = new Animal(name, gender, species);
                animalStore.push(animalInstance);
                displayAnimalList();
                resetInputFields();       // reset the input fields after submit
            }
    
            //Create a function that will display all of the animals stored in the array as an unordered list on the page.
            function displayAnimalList() {
                let template = '';
                for (let index = 0; index < animalStore.length; index++) {
                    const animal = animalStore[index];
                    template += `<tr><td>${animal.name}</td><td>${animal.gender}</td><td>${animal.species}</td></tr>`;
                }
                document.getElementById("animal-list").innerHTML = template;        // you can optimize it to not render whole list again and again- only newly animal added 
            }
    
            function resetInputFields() {
                document.getElementById('name').value = "";
                Array.from(document.getElementsByName('gender')).map(o => o.checked = false);
                document.getElementById('species').value = "";
            }
        </script>
    
    
    </body>
    
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2019-10-06
      • 2015-03-05
      • 2017-09-02
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多