首页 > 解决方案 > 完成对象数组 reverse() 和 sort() 按钮,使其在按下时起作用

问题描述

我很难完成我的代码。我有一个对象数组,我需要使用一个按钮来执行reverse()andsort()函数。我将按钮添加到我的 HTML 中,但我需要帮助在我的 javascript 中执行“功能”方法以使按钮在网页上工作。我想不通。有人请帮忙。

HTML 代码:

<html>

<head>
  <title>Lab 9</title>
</head>

<body>
  <section id="section"></section>
  <script src="Lab9.js"></script>

  <button onClick="reverse()">Reverse</button>
  <button onClick="sort()">Sort</button>
</body>
</html>

Javascript代码:

"use strict";

let motorcycles = [
    {"Color": "Red", "Type": "Honda"}, {"Color": "White", "Type": "Kawasaki"},
    {"Color": "Blue", "Type": "BMW"}, {"Color": "Black", "Type": "Yamaha"},
    {"Color": "Red & White", "Type": "Ducati"}
];

//executes the reverse() function
function reverse() {
    return motorcycles;
}
//executes the sort() function
function sort() {

}

//Unordered List
let ul = '<ul>';

//Looping through the array
for (let index = 0; index < motorcycles.length; index++) {
    let motorcycle = motorcycles[index];
    let motorcycleColor = motorcycle.Color;
    let motorcycleType = motorcycle.Type;

    ul += `<li>${motorcycleColor} ${motorcycleType}</li>`;

    console.log(motorcycleColor);
    console.log(motorcycleType);
}

ul += '</ul>';
document.getElementById("section").innerHTML = ul;

标签: javascriptarraysobject

解决方案


您用于循环数组的代码需要在函数内部才能执行,因此您调用函数反向和排序但其中没有任何内容要执行,这就是您没有得到任何结果的原因。

 function reverse() {
 let ul = '<ul>';

  //Looping through the array
  for (let index = 0; index < motorcycles.length; index++) {
      let motorcycle = motorcycles[index];
      let motorcycleColor = motorcycle.Color;
      let motorcycleType = motorcycle.Type;

      ul += `<li>${motorcycleColor} ${motorcycleType}</li>`;

      console.log(motorcycleColor);
      console.log(motorcycleType);
  }

  ul += '</ul>';
  document.getElementById("section").innerHTML = ul;
}

推荐阅读