循环返回数组中的单词

时间:2019-07-09 10:17:24

标签: javascript arrays loops

我正在使用以下脚本,每150毫秒从数组​​(全部,部分或一个)随机中获取一个单词。现在,我想不是随机地从数组中获取单词,而是在 loop 中(所以顺序为“ all”,“ some”,“ one”,“ all”,“ some” ','one'等)。我该怎么办?

var array = ['all', 'some', 'one'],
  words = null;
var getWord = function() {
  return [array[Math.floor(Math.random() * array.length)]];
};
setInterval(function() {
  words = getWord();
  $('#random-word').html(words[0]);
}, 150);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="random-word"></p>

3 个答案:

答案 0 :(得分:6)

只有一个持久计数器变量,您可以在每次调用getWord时增加该变量:

const array = ['all', 'some', 'one']
let counter = 0;
const getWord = () => array[counter++ % array.length];

setInterval(() => {
  $('#random-word').html(getWord());
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-word"></div>

或者,如果您在表达式上下文中不喜欢++

const array = ['all', 'some', 'one']
let counter = 0;
const getWord = () => {
  const word = array[counter % 3];
  counter++;
  return word;
};

setInterval(() => {
  $('#random-word').html(getWord());
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-word"></div>

答案 1 :(得分:0)

您可以使用counter并在每次大于数组长度时将其重置

var array = ['all', 'some', 'one'];
words = null;
var i = 0;
var getWord = function() {

  if (i == array.length)
    i = 0;
  return [array[i++]];
};
setInterval(function() {
  words = getWord();
  console.log(words[0]);
}, 150);

答案 2 :(得分:-1)

另一种可行的方法是创建一个自定义迭代器,该迭代器将在每次交互的允许范围内返回下一个数组索引:

var array = ['all', 'some', 'one'],
    words = null;

var iterator = (function* (min, max) {
    let pointer = min;
    while (true) {
        if (pointer > max) {
            pointer = 0
        }
        yield pointer;
        pointer++
    }
})(0, array.length - 1);

var getWord = function () {
    return [array[iterator.next().value]];
};
setInterval(function () {
    words = getWord();
    $('#random-word').html(words[0]);
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-word"></div>