如何让数组随按键递增

How to get an array to increment with keypress

我需要通过按键来增加我的数组。当我按下另一个键时,我可以显示数组的第一个元素,但无法显示数组的其他元素。

我已经使用警报来获取要通过按键显示的消息,并且可以显示数组中的第一个元素,但是当我再次按键时无法显示数组中的其他元素.

function display_phrase() {
  var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!','Forget About It!','Wooooo!','Oh Bother!'];   
  var arrayCounter = 0;
  var arrayPosition = (arrayCounter % arrayPhrase.length);

  $("#display_phrase").html("<h1>" +arrayPhrase[arrayPosition] +".</h1>");
}

var arrayCounter = 0;

$(document).ready(function() {
  $('body').keypress(function() {
    display_phrase();
    arrayCounter++;
  });
});

在您的版本中,display_phrase 将全局 arrayCounter 变量屏蔽为同名的局部变量。要修复它,请删除本地 var arrayCounter = ... 并将声明保留在更高范围内。

例如:

var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!','Forget About It!','Wooooo!','Oh Bother!'];   
var arrayCounter = 0;

function display_phrase() {
    var arrayPosition = (arrayCounter % arrayPhrase.length);

    $("#display_phrase").html("<h1>" +arrayPhrase[arrayPosition] +".</h1>");
}

...

去掉函数里面的arrayCounter。由于您有一个全局变量和一个同名的局部变量,因此在函数内部局部变量优先。

干脆去掉,让它用全局的

function display_phrase() {
  var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!', 'Forget About It!', 'Wooooo!', 'Oh Bother!'];
  //var arrayCounter = 0;
  var arrayPosition = (arrayCounter % arrayPhrase.length);

  $("#display_phrase").html("<h1>" + arrayPhrase[arrayPosition] + ".</h1>");
}

var arrayCounter = 0;

$(document).ready(function() {
  $('body').keypress(function() {
    display_phrase();
    arrayCounter++;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display_phrase"></div>