简体   繁体   English

javascript中的静态数组变量?

[英]Static array variable in javascript?

Can I create an static variable as array in javascript, What I want to do is to keep the value static even when refreshing the page. 我可以在javascript中创建一个静态变量作为数组,我想要做的是即使刷新页面时保持值静态。

I'm trying now is create a function as object like: 我现在正在尝试创建一个函数作为对象,如:

function Data(p){
    Data.point.push(p);
    Data.size++;
}
Data.size = 0; 
Data.point = [];

But then I noticed every time I refresh the page, it will reset the Data because of the last two lines. 但后来我注意到每次刷新页面时,由于最后两行,它会重置数据。

您可以使用sessionStorage在页面刷新期间保留数据。

No javascript data is preserved from one page load to the next. 从一个页面加载到下一个页面加载不会保留javascript数据。 The entire javascript context of a page is destroyed when a new page is loaded over the top of it. 当新页面加载到页面顶部时,页面的整个javascript上下文将被销毁。

Your options for saving state that survives a page load are as follows: 保存页面加载后保存状态的选项如下:

  1. Save the data in LocalStorage so future web pages can read it from there. 将数据保存在LocalStorage以便将来的网页可以从那里读取它。
  2. Save the data in a cookie so future web pages can read it from there. 将数据保存在cookie中,以便将来的网页可以从那里读取。
  3. Save the data on your server so it can be loaded into future pages automatically or so future web pages can query the server with ajax. 将数据保存在服务器上,以便将其自动加载到将来的页面中,以便将来的网页可以使用ajax查询服务器。
  4. Encode the data into a queryString and use that URL when reloading the page, then parsing the data out of the queryString when the new page loads. 将数据编码为queryString并在重新加载页面时使用该URL,然后在加载新页面时从queryString中解析数据。

Of all of these, the LocalStorage option is probably the simplest and cleanest. 在所有这些中,LocalStorage选项可能是最简单和最干净的选项。 You can read about it here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage 你可以在这里阅读: https//developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage

LocalStorage (or session storage if you want a shorter lifetime for the storage) is available in IE8 and above and all other popular browsers. IE8及更高版本以及所有其他流行的浏览器都提供LocalStorage(或者如果您希望存储的使用寿命更短的会话存储)。 The MDN article referenced above even includes a shim that will fallback to cookies if LocalStorage is not supported (eg old versions of IE). 上面引用的MDN文章甚至包括一个垫片,如果不支持LocalStorage,它将回退到cookie(例如IE的旧版本)。

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

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