我正在做一个简单的项目,用户可以将项目推送或弹出到阵列上。我的问题是,当他们按下某个项目并尝试推送另一个项目时,它不会将其添加到列表中,它只是替换它们添加到数组中的最后一个值。
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>
答案 0 :(得分:10)
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;