【问题标题】:i want the code to say the first word on the first click,the second word on the second click我希望代码在第一次点击时说出第一个词,在第二次点击时说出第二个词
【发布时间】:2019-05-10 23:31:53
【问题描述】:

我希望代码在第一次点击时说出第一个单词,在第二次点击时说出第二个单词

代码如下:

var hola = false;
var plus = 0;
var words = ['hola', 'como', 'esta']

function draw() {
  class mouse {
    click() {
      if (mouseIsPressed) {
        plus = plus + 1
      }
    }
  }
  if (mouseIsPressed) {
    textSize(50);
    text(words[0], mouseX, mouseY, 50);
  }
}

【问题讨论】:

    标签: javascript arrays function


    【解决方案1】:

    你可以使用一个数组,作为一个先进先出的数据结构(这里我称之为队列)。

    通过使用.shift(),您可以弹出集合中的第一个元素并打印它,然后继续执行此操作直到集合为空。 (您需要处理尝试弹出空对象的情况)。

    var hola = false;
    var plus = 0;
    var wordsQueue = ['hola', 'como', 'esta']
    
    function draw() {
      class mouse {
        click() {
          if (mouseIsPressed) {
            plus = plus + 1
          }
        }
      }
      if (mouseIsPressed) {
        textSize(50);
        alert(wordsQueue.shift()); //removes head of queue
      }
    }

    【讨论】:

    • 这三个同时显示我希望每次点击其中一个显示
    【解决方案2】:

    只需使用plus 访问数组中的每个元素:

    var plus = 0;
    var words = ['hola', 'como', 'esta'];
    document.body.addEventListener("click", () => {
      plus++;
      document.write(words[plus % words.length]);
    });
    body {
      height: 100vh;
      width: 100vw;
    }
    <body></body>

    【讨论】:

    • 我不想在控制台中显示它我希望当我在屏幕上单击鼠标时显示它
    • 编辑了@s.rob,还有更好的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2019-09-28
    • 2016-07-14
    相关资源
    最近更新 更多