如何仅使用Javascript一次显示一个数组元素?

时间:2018-07-07 09:04:30

标签: javascript html arrays

我制作了一个JavaScript数组随机化器,它每次间隔显示一个元素。我想让他们一次显示一个没有间隔但有按钮的显示。当我单击按钮时,它将切换到下一个元素,但是直到那时它仍保持不变。你能帮我做到吗?

var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"];

var i = 0;
setInterval(function() {
  document
    .getElementById('numberList')
    .innerHTML = numberStrings[i++];
  if (i == numberStrings.length) i = 0;
}, 2000);

function shuffleUsingRandomSwapping(array) {
  var j, x, i = 0,
    len = array.length;
  for (i; i < len; i++) {
    j = Math.floor(Math.random() * len);
    x = array[i];
    array[i] = array[j];
    array[j] = x;
  }
}
<button onclick="shuffleUsingRandomSwapping(numberStrings);updateNumberList(numberStrings);">Shuffle Using Random Swapping</button>

<div id="numberList"></div>

1 个答案:

答案 0 :(得分:1)

var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"];

var curElement = 0;

function updateNumberList() {
  document
      .getElementById('numberList')
      .innerHTML = numberStrings[curElement++];
    if (curElement == numberStrings.length) curElement = 0;
}

function shuffleUsingRandomSwapping(array) {
  var j, x, i = 0,
    len = array.length;
  for (i; i < len; i++) {
    j = Math.floor(Math.random() * len);
    x = array[i];
    array[i] = array[j];
    array[j] = x;
  }
}
<button onclick="shuffleUsingRandomSwapping(numberStrings);updateNumberList(numberStrings);">Shuffle Using Random Swapping</button>

<div id="numberList"></div>

我不知道您的情况,但是如果您只是想在每次按下按钮时显示数组中的随机元素,则应该以一种更加简单的方式来完成操作,而不必重新排列数组。

var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"];

function displayRandomElem() {
  document
      .getElementById('numberList')
      .innerHTML = numberStrings[Math.floor(Math.random() * numberStrings.length)];
}
<button onclick="displayRandomElem()">Shuffle Using Random Swapping</button>

<div id="numberList"></div>

要以随机顺序显示值,以免重复出现,请使用以下代码:

var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"];

function displayRandomElem() {
  if (numberStrings.length == 0) return;

  document
      .getElementById('numberList')
      .innerHTML = numberStrings.splice(Math.floor(Math.random() * numberStrings.length), 1);
}
<button onclick="displayRandomElem()">Shuffle Using Random Swapping</button>

<div id="numberList"></div>