Javascript JS如何缓存一个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14266730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS how to cache a variable
提问by Bluefire
What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the simplest way to do that? JQuery answers are welcome.
我想要做的是能够创建一个变量,给它一个值,关闭并重新打开窗口,并能够检索我在上次会话中设置的值。最简单的方法是什么?欢迎使用 JQuery 答案。
回答by Denys Séguret
Use localStoragefor that. It's persistent over sessions.
为此使用localStorage。它在会话中持续存在。
Writing :
写作 :
localStorage['myKey'] = 'somestring'; // only strings
Reading :
读 :
var myVar = localStorage['myKey'] || 'defaultValue';
If you need to store complex structures, you might serialize them in JSON. For example :
如果您需要存储复杂的结构,您可以将它们序列化为 JSON。例如 :
Reading :
读 :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};
Writing :
写作 :
localStorage['myKey'] = JSON.stringify(myVar);
Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.
请注意,您可以使用多个键。它们都将被同一域中的所有页面检索到。
Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
除非你想兼容IE7,否则你没有理由使用过时的小cookie。
回答by Kevin Boucher
You have three options:
您有三个选择:
- Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
- DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
- If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)
- Cookie:https: //developer.mozilla.org/en-US/docs/DOM/document.cookie
- DOMStorage(sessionStorage 或 localStorage):https: //developer.mozilla.org/en-US/docs/DOM/Storage
- 如果您的用户已登录,您可以将数据保存在以用户(或组)为键的服务器数据库中
回答by tam tam
You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.
如果您的要求允许,您可能会创建一个 cookie。如果您选择采用 cookie 路线,那么解决方案可能如下。cookie 的另一个好处是在用户关闭浏览器并重新打开后,如果 cookie 没有被删除,该值将被保留。
Cookie*Create and Store a Cookie:*
Cookie*创建和存储 Cookie:*
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The function which will return the specified cookie:
将返回指定 cookie 的函数:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Display a welcome message if the cookie is set
如果设置了 cookie,则显示欢迎消息
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.
上面的解决方案是通过cookies来保存值。这是一种非常标准的方式,无需在服务器端存储值。
Jquery
查询
Set a value to the session storage.
为会话存储设置一个值。
Javascript:
Javascript:
$.sessionStorage( 'foo', {data:'bar'} );
Retrieve the value:
检索值:
$.sessionStorage( 'foo', {data:'bar'} );
$.sessionStorage( 'foo' );Results:
{data:'bar'}
Local StorageNow lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:
本地存储现在让我们来看看本地存储。例如,假设您有一个要保留的变量数组。你可以这样做:
var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);
//...
var storedNames=JSON.parse(localStorage['names']);
Server Side Example using ASP.NET
使用 ASP.NET 的服务器端示例
Adding to Sesion
添加到会话
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
// When retrieving an object from session state, cast it to // the appropriate type.
// 从会话状态检索对象时,将其强制转换为 // 适当的类型。
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
I hope that answered your question.
我希望回答了你的问题。
回答by HoangND
check out my js lib for caching: https://github.com/hoangnd25/cacheJS
查看我的 js 库进行缓存:https: //github.com/hoangnd25/cacheJS
My blog post: New way to cache your data with Javascript
我的博客文章: 使用 Javascript 缓存数据的新方法
Features:
特征:
- Conveniently use array as key for saving cache
- Support array and localStorage
- Clear cache by context (clear all blog posts with authorId="abc")
- No dependency
- 方便地使用数组作为保存缓存的键
- 支持数组和本地存储
- 按上下文清除缓存(清除所有带有 authorId="abc" 的博客文章)
- 无依赖性
Basic usage:
基本用法:
Saving cache:
保存缓存:
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});
Retrieving cache:
检索缓存:
cacheJS.get({blogId: 1,type: 'view'});
Flushing cache
刷新缓存
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
cacheJS.removeByContext({author:'hoangnd'});
Switching provider
切换供应商
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};
回答by sidverma
I have written a generic caching func()which will cache any variable easily and very readable format.
Caching function:
我写了一个泛型caching func(),它可以轻松地缓存任何变量,并且格式非常可读。
缓存功能:
function calculateSomethingMaybe(args){
??return args;
}
function caching(fn){
??const cache = {};
??return function(){
????const string = arguments[0];
????if(!cache[string]){
??????const result = fn.apply(this, arguments);
??????cache[string] = result;
??????return result;
????}
????return cache[string];
??}
}
const letsCache = caching(calculateSomethingMaybe);
console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));

