Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hiển thị phần tử mảng theo thứ tự ngược khi click button trong JavaScript

Dùng biến đếm ngược từ length - 1, mỗi lần click giảm index, quay vòng khi < 0.

Ví dụ


<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hiển thị ngược mảng</title>
</head>
<body>
    <div id="display" style="text-align:center; font-size:20px; margin:20px;"></div>
    <button onclick="showReverse()">Hiển thị phần tử tiếp theo (ngược)</button>

    <script>
        var names = ['John', 'David', 'Bob'];
        var index = names.length - 1; // Bắt đầu từ cuối

        function showReverse() {
            document.getElementById('display').innerHTML = names[index];
            index--;
            if (index < 0) index = names.length - 1; // Quay vòng
        }
    </script>
</body>
</html>

Cách chạy

Lưu index.html, mở Live Server, click button nhiều lần.

Kết quả

Lần 1: "Bob" → Lần 2: "David" → Lần 3: "John" → Lần 4: "Bob" (lặp lại)...

Cách khác: Dùng unshift() + pop() xoay vòng mảng, hoặc generator function.