【问题标题】:How to display javascript array items one at a time in reverse?如何反向显示javascript数组项目一次?
【发布时间】:2020-11-09 04:55:20
【问题描述】:
我有一个按钮,每次按下时都会显示一个数组字符串,按从上到下的顺序显示。我试图找出一种从下到上显示字符串的方法(相反的顺序)。我在下面添加了两个 sn-ps 以显示到目前为止我所拥有的。顶部的 sn-p 是按正序显示数字的功能按钮,底部的 sn-p 是我迄今为止尝试反转功能的按钮,但无济于事。需要做什么来告诉函数先显示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>
【问题讨论】:
标签:
javascript
html
arrays
function
reverse
【解决方案1】:
为了使您的代码正常工作,您应该删除 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>
【解决方案2】:
使用它可以避免使用全局 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>