简体   繁体   English

JavaScript全局变量在PageLoad上重新初始化

[英]JavaScript Global Variable Re-initialized on PageLoad

On Pageload I perform some functions to show data. 在Pageload上,我执行一些功能来显示数据。 My global var is getting re-initialized on the page load and I can't use it to store data. 我的全局变量在页面加载时被重新初始化,因此我无法使用它来存储数据。 Can someone explain? 有人可以解释吗?

var busesWithProblems = []; //declared as global - this keeps getting reinitialized 

(function () {
    .... doing stuff
    for (var i = 1; i <= 4; i++) {
        busesWithProblems = something;
}

The JS runtime gets reinitialised when you refresh the page. 刷新页面时,JS运行时将重新初始化。 That's the usual state of affairs since browsers where first introduced. 自从首次引入浏览器以来,这就是通常的情况。

You can use LocalStorage to store data permanently - until the user clears his cache, or SessionStorage to store data until the user exits your domain 您可以使用LocalStorage永久存储数据-直到用户清除其缓存,或者使用SessionStorage存储数据直到用户退出您的域

Bear in mind that those 2 methods only store String s. 请记住,这两个方法仅存储String

So if you want to save a complex variable you would have to JSON.stringify() it when saving, and JSON.parse() it when getting it back - This answer goes into more detail for this 因此,如果您想保存一个复杂的变量,则在保存时必须对其进行JSON.stringify() ,在返回时必须对其进行JSON.parse() -有关此问题的更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM