[英]How to display javascript array items one at a time in reverse?
我有一個按鈕,每次按下時都會顯示一個數組字符串,按從上到下的順序。 我正在嘗試找出一種從下到上(相反順序)顯示字符串的方法。 我在下面添加了兩個片段來展示我到目前為止所得到的。 頂部片段是按正序顯示數字的功能按鈕,底部片段是我迄今為止嘗試反轉 function 的功能按鈕,但無濟於事。 需要做什么來告訴 function 先顯示888
,然后顯示777
、 666
、 555
等等?
var textCount = 0; var oddtext = [ '111', '222', '333', '444', '555', ] function newThing() { document.getElementById('thingDisplay').innerHTML = oddtext[textCount]; textCount++; if (textCount >= oddtext.length) textCount = 0; }
<div align="center" id='thingDisplay'></div> <button class="box" id="button01" onclick="newThing()">New Thing</button>
var textCount = 0; var oddtext = [ '111', '222', '333', '444', '555', ] function newThing() { oddtext.reverse(); document.getElementById('thingDisplay').innerHTML = oddtext[textCount]; textCount++; if (textCount >= oddtext.length) textCount = 0; }
<div align="center" id='thingDisplay'></div> <button class="box" id="button01" onclick="newThing()">New Thing</button>
使用它避免了對全局textCount
變量的需要:
const oddtext = ['111', '222', '333', '444', '555', '666', '777', '888']; const thingDisplay = document.getElementById('thingDisplay'); thingDisplay.innerHTML = oddtext[oddtext.length - 1]; function newThing() { const { innerHTML } = thingDisplay; const { length } = oddtext; const index = ((oddtext.indexOf(innerHTML) - 1) + length) % length; thingDisplay.innerHTML = oddtext[index]; }
<div align="center" id='thingDisplay'></div> <button class="box" id="button01" onclick="newThing()">New Thing</button>
為了使您的代碼正常工作,您應該刪除reverse()
並從數組的長度 -1 一直到 0
var oddtext = [ '111', '222', '333', '444', '555', '666', '777', '888' ] textCount=oddtext.length-1 function newThing() { document.getElementById('thingDisplay').innerHTML = oddtext[textCount]; textCount--; if (textCount<0) textCount=oddtext.length-1 }
<div align="center" id='thingDisplay'></div> <button class="box" id="button01" onclick="newThing()">New Thing</button>
或者,如果要使用反向,則必須從索引0
開始計數到array.length-1
var oddtext = [ '111', '222', '333', '444', '555', '666', '777', '888' ] oddtext.reverse() var textCount = 0; function newThing() { document.getElementById('thingDisplay').innerHTML = oddtext[textCount]; textCount++; if (textCount>oddtext.length-1) textCount=0 }
<div align="center" id='thingDisplay'></div> <button class="box" id="button01" onclick="newThing()">New Thing</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.