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

JavaScript修改的数组值切换HTML页面后重置的解决方法

页面跳转后如何保持JavaScript数组的内容?

我在JavaScript中定义了一个空数组Counter,执行test()函数时,希望向数组中添加值并切换HTML页面。但在第二个页面中使用console.log(Counter)输出时,数组为空。请问如何在切换页面时保持数组中的值?代码如下:

var Counter = [];
function test() {
  Counter.push("1")
  window.location.replace("page2.html")
}

这个问题太常见啦——每次页面跳转,浏览器都会重新加载新页面的JavaScript运行环境,原来页面里定义的变量自然就被清空了,所以page2.html里根本拿不到之前的Counter数组。给你几个实用的解决办法,根据你的需求选就行:

方法一:用localStorage持久化存储

localStorage可以把数据存在浏览器本地,哪怕关闭浏览器再打开,数据也不会丢,适合需要长期保留的场景。修改你的代码:

function test() {
  // 先从localStorage取出已有数据,没有的话初始化空数组
  let Counter = JSON.parse(localStorage.getItem('counter')) || [];
  Counter.push("1");
  // 把数组转成字符串存回去(localStorage只能存储字符串类型)
  localStorage.setItem('counter', JSON.stringify(Counter));
  window.location.replace("page2.html");
}

然后在page2.html里这样读取:

let Counter = JSON.parse(localStorage.getItem('counter')) || [];
console.log(Counter); // 就能看到["1"]啦

💡 注意:localStorage是同源页面共享的,如果不需要这个数据了,记得用localStorage.removeItem('counter')手动清理。

方法二:用sessionStorage临时存储

如果只希望数据在当前浏览器会话中保留(关闭浏览器就自动清空),那sessionStorage更合适,用法和localStorage几乎完全一样:

function test() {
  let Counter = JSON.parse(sessionStorage.getItem('counter')) || [];
  Counter.push("1");
  sessionStorage.setItem('counter', JSON.stringify(Counter));
  window.location.replace("page2.html");
}

page2.html里读取的代码:

let Counter = JSON.parse(sessionStorage.getItem('counter')) || [];
console.log(Counter);

方法三:通过URL参数传递数据

如果你的数组数据量很小(比如例子里只有一个元素),可以直接把数据拼在URL后面传递给page2.html:

function test() {
  let Counter = [];
  Counter.push("1");
  // 把数组转成字符串并编码,避免URL解析问题
  const counterStr = encodeURIComponent(JSON.stringify(Counter));
  window.location.replace(`page2.html?counter=${counterStr}`);
}

然后在page2.html里解析URL参数:

// 解析URL里的查询参数
const urlParams = new URLSearchParams(window.location.search);
const counterStr = urlParams.get('counter');
// 解码并转成数组,没有的话初始化空数组
const Counter = counterStr ? JSON.parse(decodeURIComponent(counterStr)) : [];
console.log(Counter);

⚠️ 这个方法只适合小数据,因为URL有长度限制,数据太多的话会出问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:52:37