按下时,完成对象数组的reverse()和sort()按钮使其起作用

时间:2018-12-06 22:35:52

标签: javascript arrays object

我在完成代码方面遇到困难。我有一个对象数组,需要使用一个按钮来执行reverse()sort()函数。我将按钮添加到HTML中,但是我需要在JavaScript中执行“ function”方法的帮助才能使按钮在网页上正常工作。我不知道。有人帮忙。

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;

2 个答案:

答案 0 :(得分:0)

您要在数组中循环的代码必须在函数内部才能执行,因此您调用函数的过程将反向进行并进行排序,但其中没有任何执行要执行的操作,因此未得到任何结果。

 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;
}

答案 1 :(得分:0)

我想您在这里有几个不同的问题。可能有帮助的第一点只是看到Array.sort起作用:

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

const sortedMotorcycles = motorcycles.sort( (a, b) => {
  return a.Type.localeCompare(b.Type)
})

console.log(sortedMotorcycles)

对于字符串比较,String.localeComparison在默认情况下可以很好地完成字母排序。一旦创建了该数组,就可以对其进行迭代以生成HTML元素。尽管您可能希望避免由于字符串附带的脚本注入问题而直接将字符串传递到innerHTML中。