สมมติว่าต่อไปนี้คืออาร์เรย์ของเรา –
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.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/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)” และคลิกขวาที่ไฟล์ เลือกตัวเลือก “เปิดด้วย Live Server” ในตัวแก้ไข VS Code
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

ขั้นตอนที่ 1
เมื่อคุณคลิกปุ่ม คุณจะได้รับค่าสุดท้ายของอาร์เรย์ สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

ขั้นตอนที่ 2
อีกครั้ง คลิกที่ปุ่ม คุณจะได้รับค่าที่สองสุดท้าย สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
