Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 300
Griz Avatar asked Sep 02 '26 09:09

Griz


1 Answers

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

like image 168
GregL Avatar answered Sep 04 '26 23:09

GregL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!