如何在数组javascript中列出项目

时间:2016-02-16 05:59:19

标签: javascript html

一直在研究这段代码。我想让它生成我的数组,所以它看起来像这样:

[0] cat

[1] dog

[2] *Whatever value entered by user*

目前,它产生了这个

Pushed: *User Entered Value*

cat,dog,*user entered value*

这是我的代码。

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

3 个答案:

答案 0 :(得分:1)

我会改变:

while (push != null) {}

表示if,因为该段代码永远不会执行。

if (push != null) {}

答案 1 :(得分:1)

首先,上面的代码会导致无限循环,因为push永远不会重新初始化为null。

以下是我提出的建议:

<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>

这是一个小提琴,可以帮助你。

https://jsfiddle.net/vozhuuq4/

答案 2 :(得分:-1)

您可以将数值存储在数组中作为属性

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