javascript - 完成对象数组 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;
解决方案
您用于循环数组的代码需要在函数内部才能执行,因此您调用函数反向和排序但其中没有任何内容要执行,这就是您没有得到任何结果的原因。
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;
}
推荐阅读
- javascript - 多个猫头鹰轮播导航不起作用
- python - 使用 virtualenv 在 django 中创建了新项目,并且运行良好,但是当我尝试使用“startapp”创建新应用程序并再次运行项目时
- javascript - 使用 JavaScript 访问 HTML 中的标签标记
- java - 无法让 servlet 建立与我的 jsp 文件的连接,不断收到 404 错误
- go - Go接口返回类型
- python - 裁剪图像python的边框
- loops - 如何在 Pygame 中与两个精灵发生碰撞?如何继续 Sprite 循环?
- javascript - 从自定义目录文件创建 webpack 包
- libreoffice-calc - LibreOffice 基本版中的 Instr 函数不区分大小写?
- java - 如何从 SMSC 标头中检索可选参数(即 SAR_MSG_REF_NUM、SAR_SEGMENT_SEQNUM、SAR_TOTAL_SEGMENTS)我们正在使用 JSMPP jar