Griz
Griz

Reputation: 65

How to List items in array javascript

been working on this code. I want it to produce my array so it looks like this:

[0] cat

[1] dog

[2] *Whatever value entered by user*

Currently, it produces this

Pushed: *User Entered Value*

cat,dog,*user entered value*

Here's my code.

var array = ["cat", "dog"];
window.onload = 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 = "Pushed: " + "<em>" + push + "</em>" + "<br>" + "<br>" + array.toString() + "<hr>";
        menu();
        }
    } 
} 

Upvotes: 0

Views: 84

Answers (3)

coffeeguy
coffeeguy

Reputation: 51

First of all, the above code would result in infinite loop as push is never reinitialized to null.

Here is what I come up with:

<script>
var array = ["cat", "dog"];
window.onload = 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.");
var push = null;
var index = 0;
  if (selection == '1'){
     push = prompt("What item would you like to push onto the array?");
      while (push != null) {    
        array.push(push);
       // document.getElementById("pushed").innerHTML = "Pushed: " + "<em>" + push + "</em>" + "<br>" + "<br>" + array.toString() + "<hr>";

       var html = "Pushed: <em>" + push + "</em><br>";
       var list = '';
       var len = array.length;
       for(var i = 0;i<len;i++){
       list = list +"["+i+"] "+array[i]+'<br/>';
       }
       document.getElementById("pushed").innerHTML = html+list;
         // make push null to avoid infinite loop.
       push= null;
        menu();
        }
    } 
} 

</script>

Here is a fiddle, which can help you.

https://jsfiddle.net/vozhuuq4/

Upvotes: 1

melalonso
melalonso

Reputation: 228

I would change the:

while (push != null) {}

for an if, because that piece of code is never executing.

if (push != null) {}

Upvotes: 1

Harsh shah
Harsh shah

Reputation: 46

You can store value in array as properties

var array = [];
window.onload = 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[array.length-1] = push;
    document.getElementById("pushed").innerHTML = "Pushed: " + "<em>" + push + "</em>" + "<br>" + "<br>" + array.toString() + "<hr>";
    menu();
    }
 } 
} 

Upvotes: -1

Related Questions