You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript新手求助:使用push方法添加元素后数组无法打印

问题分析与解决方案

你遇到的问题核心是**document.write()在页面加载完成后调用会覆盖整个文档**,导致原来的页面元素(输入框、按钮、列表容器)都被清空,看起来像是数组没打印出来,实际上页面已经被重写了,后续获取list_items元素的操作也会因为元素不存在而失效,只是浏览器没有抛出明显报错。

具体问题点

在你的display()函数里,这行代码是罪魁祸首:

document.write("Array items are:<br>" );

当页面已经完全加载(比如你点击按钮的时候),调用document.write()会自动触发document.open(),这会直接清空当前的HTML文档。所以后续你试图获取list_items元素并添加子元素的操作,其实是在一个全新的空文档里执行的,自然看不到预期的效果。

修复后的代码

我们需要修改display()函数,去掉document.write(),改为直接操作list_items容器:先清空容器里的旧内容,再重新渲染数组元素,同时可以添加标题文本到容器里。

修改后的完整代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Array Operations</title>
</head>
<body>
<input type="text" id="item" >
<br>
<br/>
<input type="button" value="Push" onClick="Push()"> &nbsp;
<input type="button" value="Pop" onClick="Pop()"> &nbsp;
<input type="button" value="Shift" onClick="Shift()"> &nbsp;
<input type="button" value="UnShift" onClick="UnShift()">
<div id="list_items"> </div>
<script type="text/javascript">
var arra1=[12,34,56,67,78,89,87];

function display() {
  var lists=document.getElementById('list_items');
  // 先清空容器的旧内容
  lists.innerHTML = "";
  // 添加标题
  var title = document.createElement('div');
  title.textContent = "Array items are:";
  lists.appendChild(title);
  // 遍历数组添加元素
  for(var i=0;i<arra1.length;i++) {
    var para = document.createElement('div');
    para.textContent = arra1[i];
    lists.appendChild(para);
  }
}

// 页面加载完成后先初始化显示数组
window.onload = function() {
  display();
};

function Push() {
  var item1=document.getElementById("item").value;
  // 可选:转为数字类型,避免存入字符串
  // item1 = parseInt(item1, 10);
  if(item1) { // 简单判断输入不为空
    arra1.push(item1);
    display();
    document.getElementById("item").value = ""; // 清空输入框
  }
}

function Pop() {
  if(arra1.length > 0) { // 避免空数组执行pop
    arra1.pop();
    display();
  }
}

// 补充你未实现的Shift和UnShift函数示例
function Shift() {
  if(arra1.length > 0) {
    arra1.shift();
    display();
  }
}

function UnShift() {
  var item1=document.getElementById("item").value;
  if(item1) {
    // 可选:转为数字类型
    // item1 = parseInt(item1, 10);
    arra1.unshift(item1);
    display();
    document.getElementById("item").value = "";
  }
}
</script>
</body>
</html>

关键改进点

  • 移除了document.write(),改为直接操作目标容器list_items
  • 添加了window.onload事件,页面加载完成后自动显示初始数组
  • 每次调用display()前先清空容器,避免重复添加元素
  • 增加了简单的输入校验(非空判断)和数组操作的边界判断(避免空数组执行pop/shift)
  • 操作完成后清空输入框,提升用户体验

这样修改后,点击Push或其他按钮时,数组的变化就会正确显示在页面上,不会再出现页面被覆盖的问题了。

内容的提问来源于stack exchange,提问作者Gunjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:31:27