【问题标题】:How to get an array to increment with keypress如何通过按键使数组递增
【发布时间】:2019-02-18 23:46:43
【问题描述】:

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

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

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++;
  });
});

【问题讨论】:

  • 与Java无关,所以我删除了问题标签。相反,它看起来与 JavaScript 相关,因此我添加了该标签。为您的问题吸引错误的专家是没有意义的。
  • display_phrase 有一个局部变量 arrayCounter 在方法中优先于全局变量。删除它。
  • arrayCounter 正在重新分配给display_phrase 中的0。将arrayCounter 的作用域提高到display_phrase 函数之上。

标签: javascript jquery arrays increment keypress


【解决方案1】:

在您的版本中,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>");
}

...

【讨论】:

  • 方法内部的变量不会重置它。由于使用了var,它是一个完全不同的变量
  • 对,但它掩盖了全局变量。这样arrayPosition 中的用法总是引用值为 0 的本地用法。
  • 我的意思主要是“重置”的用法不正确。重置某些东西意味着它的价值被改变了。但不是在这种情况下。由于内部变量,全局变量没有变化。
  • 是的,你是对的。我最初的措辞并不准确。
【解决方案2】:

删除函数内部的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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2018-09-02
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多