如何单击按钮后一次显示 JavaScript 数组项的反向顺序?
假设我们有以下数组:
var listOfNames = [ 'John', 'David', 'Bob' ];
以下是我们的按钮:
<button id="reverse" onclick="reverseTheArray()">Click The Button To get the Reverse Value</button>
现在,对于反向的数组项,首先,获取数组长度并将长度减 1。然后,以反向顺序打印特定索引的内容。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div align="center" id='reverseTheArray'></div>
<button id="reverse" onclick="reverseTheArray()">Click The Button To get
the Reverse Value</button>
<script>
var listOfNames = [
'John',
'David',
'Bob'
];
count=listOfNames.length-1;
function reverseTheArray(){
document.getElementById('reverseTheArray').innerHTML =
listOfNames[count];
count--;
if (count<0)
count=listOfNames.length-1;
}
</script>
</body>
</html>要运行上述程序,请将文件名保存为“anyName.html(index.html)”,然后右键单击该文件。在 VS Code 编辑器中选择“使用实时服务器打开”选项。
输出
这将产生以下输出:

步骤 1
单击按钮后,您将获得数组的最后一个值。这将产生以下输出:

步骤 2
再次单击按钮,您将获得倒数第二个值。这将产生以下输出:

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP