如何單擊按鈕後一次顯示 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.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)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用即時伺服器開啟”選項。

輸出

這將產生以下輸出:

步驟 1

單擊按鈕後,您將獲得陣列的最後一個值。這將產生以下輸出:

步驟 2

再次單擊按鈕,您將獲得倒數第二個值。這將產生以下輸出:

更新於:2020年9月9日

679 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告