javascript - 推送在 javascript 中无法正常工作

标签 javascript html

我正在做一个简单的项目,用户可以将项目插入或弹出到数组中。我的问题是,当他们插入一个项目并尝试插入另一个项目时,它不会将其添加到列表中,它只是替换他们添加到数组中的最后一个值。

window.onload = function menu(){
var array = ["cat", "dog"];
var selection = prompt("Please use this menu, and type 1 to push an item on the array, 2 to pop an item off the array, and 3 to exit the menu.");

if (selection == '1'){
  var push = prompt("What item would you like to push onto the array?");
    while (push != null) {  
      array.push(push);
      document.getElementById("pushed").innerHTML = array.toString();
      menu();
}}

然后在下面我有一个 HTML 页面,但这里是它显示的地方:

<div id = "pushed"></div>

最佳答案

menu() 函数在每次调用时都会重新定义数组,而不是在其范围之外修改数组。

var array = ['cat', 'dog']; 行移到顶部以解决这个紧迫的问题。

var array = ["cat", "dog"];

function menu(){
    var selection = prompt("Please use this menu, and type 1 to push an item on the array, 2 to pop an item off the array, and 3 to exit the menu.");
    if (selection == '1'){
      var push = prompt("What item would you like to push onto the array?");
      while (push != null) {  
          array.push(push);
          document.getElementById("pushed").innerHTML = array.toString();
          menu();
        }
      }
}
window.onload = menu;

引用资料

JS Scope

onload usage

关于javascript - 推送在 javascript 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420716/

相关文章:

javascript - Node.js 安装向导在 Windows 7 32 位上过早结束

javascript - d3 具有不正确值的多系列图表

javascript - fabricjs 删除背景图片

javascript - 如何一个接一个地执行 jquery 函数(以及其他几个问题)

javascript - 使用 AngularJS 更新 cookie

javascript - 无法显示之后添加的元素

javascript - Google map 标记出现在 Chrome 中,但不出现在 Firefox 或 IE 中

jquery - 如何自定义DevExtreme数据网格确认消息

html - 当鼠标在公共(public) block 外时如何使动画结束?

javascript - 如何制作动画标题以显示在手机和平​​板电脑上?