简体   繁体   中英

Push not working properly in javascript

I am doing a simple project where users can push or pop items onto the array. My problem is, when they push an item on and try to push another on, it doesn't add it onto the list, it simply replaces the last value that they added to the array.

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

Then down below I have an HTML page, but here is where it displays:

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

The menu() function redefines the array every time it is called, rather than modifying an array outside its scope.

Move the var array = ['cat', 'dog']; line to the top to solve this immediate problem.

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;

References

JS Scope

onload usage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM